R for Spatial Statistics

 

Rasters

R has the ability to read raster file formats but you'll need to install some additional packages. Once you read or create a raster, you can use it as you would other vectors and matricies.

Required Packages

Install the "raster" and "rgdal" packages. "Raster" contains a set of classes for working with raster data and "rgal" includes the GDAL OpenSource library for reading and writing Geospatial file formats. This includes TIFF, GeoTIFF, IMG, and over 100 others. Installing these packages may also load a series of other libraries and it will take a while. Progress bars and error messages may appear behind R Studio so you may want to minimize it or move it out of the way.

After installing the packages, load the libraries.

library(raster)
library(rgdal)

Reading Raster Files

Once you have the libraries loaded it is easy to read an existing raster file.

AnnualMeanTemp=raster("C:/ProjectsModeling/Cali_5minute/bio_1_AnnualMeanTemp_2.img")
AnnualMeanTemp=raster("C:/ProjectsModeling/Cali_5minute/DEM.tif")

You can also use a "File Chooser" dialog to open an existing file as follows.

FilePath=file.choose()
TheRaster=raster(FilePath)

Again, R Studio will open the file chooser dialog behind its main window so you may need to minimize it.

Saving Raster Files

It's also easy to write a raster to a new file.

FilePath=file.choose()
writeRaster(TheRaster, FilePath)