R for Spatial Statistics


Packages, Libraries, and Source Files

One of the real strengths of R is the huge number of packages that are available to extent its functionality and how easy it is to add the packages to your version of R. Packages contain libraries that contain functions you can call from R. You can also create source files containing functions that you use commonly and include them in mulitple R scripts.

Installing Packages

You can install a package either from the "Tools" menu in RStudio or with code. To use RStudio, select "Tools -> Install Packages...". Enter the name of the package and press "Install".

To install a package in code use the "install.packages()" function. You only need to install a package once for each install of R so I would put these lines in a separate R script with all the packages you are using and then run it when needed.


While you can specify multiple packages in a single call, I highly recommend installing packages one at a time. Some packages will install other packages and some will lock up on installation. Also, R Studio has a habit of putting dialogs behind its main window where you cannot see them. If R appears to hang, minimize it to see if there is a dialog waiting for you.

Using Libraries

You will need to "load" the package by calling "library()" in each script that wants to use the package.

scatterplot3d(mtcars$mpg,mtcars$wt,mtcars$disp, main="3D Scatterplot of Cars")

The "library()" function will throw an error if there is a problem loading the library. You can also use "required()" which will output an error and then continue execution.

Source Files

There are some "source files" that are distributed on the web that contain functions you'll want use. You can also create your own files that contain functions you can then call from mulitple scripts. This is an easy way to create "reusable" code libraries.

To includes a source file in a script, use the function "source(FilePath)" as below. Note that all R scripts have the extension "R".