Skip to main content

10.1 Raster data in R

Packages

library(terra)
library(ggplot2)
library(tidyterra)

Raster data

Today, we’ll work with spatial data in R. One special type of spatial data are raster. Raster consist of cells (pixels) that are arranged as rows and columns in a regular grid. Examples of raster data are digital elevation models (DEM), gridded climate or meteorological variables, satellite images, discrete maps such as land cover maps, and continuous maps of vegetation cover, biophysical variables, and soil variables. Common raster file formats are the GeoTiff (suffix .tif), IMAGINE (suffix .img), and NetCDF (suffix .nc). There are many more formats, but most of them can be read and written in R.

The terra package

The terra package (Hijmans et al., 2026) is the main package for creating, reading, manipulating, and writing raster data. The terra package supersedes the older raster package developed by the same team of authors. Because raster has been around for a longer time, dependencies with some packages may still exist. But development of raster will eventually be stopped at some point. You can install the latest version of terra from CRAN with install.packages("terra"). You’ll find an online documentation and tutorials for the package on the R Spatial website (Hijmans, 2026). I also recommend you scroll through the package description to get a first overview of the functationality of the package.

?`terra-package`

The terra package defines a number of spatial classes. The most important ones are:

  • SpatRaster to store raster data

  • SpatVector to store spatial vector data, i.e., points, lines, polygons.

  • SpatExtent to store information on spatial extent

SpatRaster from scratch

The rast function creates a SpatRaster object. One can create a SpatRaster from scratch, from a filename, or from another object. Below, we create a SpatRaster from scratch by specifying dimensions and spatial extent.

r <- rast(nrows=40, ncols=20, xmin=0, xmax=10, ymin=0, ymax=10)
r
class       : SpatRaster
size        : 40, 20, 1  (nrow, ncol, nlyr)
resolution  : 0.5, 0.25  (x, y)
extent      : 0, 10, 0, 10  (xmin, xmax, ymin, ymax)
coord. ref. : lon/lat WGS 84 (CRS84) (OGC:CRS84)

Object r has the structure of a SpatRaster but it does not contain any values. We can access the values of a SpatRaster with the function values. Here, we create a vector of random numbers with a length that is equal to the number of raster cells and assign it to the pixel values of the SpatRaster object.

values(r) <- runif(ncell(r))

Similarly, we can extract the values of a SpatRaster and assign them to a numerical vector v. You’ll see v is actually a matrix with the dimensions (x, y), where x is the number of cells in a layer, and y is the number of layers. The SpatRaster r has 800 cells (pixels) and 1 layer.

v <- values(r)
dim(v)
[1] 800   1
head(v)
         lyr.1
[1,] 0.5393288
[2,] 0.5683799
[3,] 0.5653591
[4,] 0.8242257
[5,] 0.4775377
[6,] 0.9479373

We can plot the SpatRaster object using the familiar plot function.

plot(r)

Manipulate SpatRaster

You can manipulate the pixel values of that layer by applying basic functions and operations.

q <- 100 * r^2
plot(q)

# create a binary mask based on a logical expression
m <- q < 10 
plot(m)

Our SpatRaster r and q have only a single layer. We can stack both layers together using the concatenate function c().

p <- c(r, q)

# assign meaningful names to the layers
names(p) <- c("random", "scaled_random")

plot(p)

Summary functions (min, max, mean, prod, sum, median, cv, any, all) yield a single value for every pixel (or two values when using range). So, they always return a SpatRaster object with a single layer (or two layers in case of range). The following code calculates for every pixel in SpatRaster p, the mean value across the two layers.

ma <- mean(p)
plot(ma)

If you want a single value summarizing all pixel values, e.g. mean pixel value for each layer, use global.

global(p, fun="mean")
                    mean
random         0.4993983
scaled_random 33.3038836
NoteMissing values and na.rm

Real raster data often contain NA cells, e.g. ocean pixels in a land surface dataset or pixels outside the study area. By default, summary functions and global return NA if any of the values involved is NA. Set na.rm=TRUE to ignore missing values in the calculation, e.g. mean(p, na.rm=TRUE) or global(p, fun="mean", na.rm=TRUE).

You can also use the square brackets to access and replace values in a raster. The example below shows how to truncate a value range, i.e., all values less than 0.5 are replaced with the value 0.5.

r[r < 0.5] <- 0.5
plot(r, range=c(0,1))

The function app provides a more generic interface to do a computation for a single SpatRaster. The function takes a SpatRaster and the function you want to apply. The function below replace all values less than and equal to 0.5 with NA. Note, this is just a simple example. The idea here is to facilitate the application of more complex functions from you or other packages.

myFunction <- function(x){ x[x <= 0.5] <- NA; return(x)}
w <- app(r, fun= myFunction)
plot(w, range=c(0,1))

Read SpatRaster from a filename

Usually, we create a SpatRaster object from a filename. The resulting object (here s) represents a connection to the physical file on disc, but does not store the file in memory. This is helpful when opening large raster files. Type the object into the console to print important metadata of the raster including dimensions, coordinate reference system, extent, layer names, etc.

s <- rast("data/chelsa_bio_1981-2010_V.2.1_europe.tif")
s
class       : SpatRaster
size        : 306, 347, 19  (nrow, ncol, nlyr)
resolution  : 15000, 15000  (x, y)
extent      : 2325000, 7530000, 1170000, 5760000  (xmin, xmax, ymin, ymax)
coord. ref. : ETRS89-extended / LAEA Europe (EPSG:3035)
source      : chelsa_bio_1981-2010_V.2.1_europe.tif
names       : bioclim1, bioclim2, bioclim3, bioclim4, bioclim5, bioclim6, ...
min values  :     -242,       13,       94,     2129,      -93,     -362, ...
max values  :      261,      154,      485,    13502,      453,      127, ...

It is good practice to give layers short but meaningful names. The layer names become variable (column) names later on, e.g. when you extract values into a data.frame or use the layers as predictors in a statistical model. Short, interpretable names make your code, model formulas, and outputs much easier to read. Also watch out for white space and special characters (e.g. -, /, (, %, °) in layer names. They are not valid in R variable names and may cause problems down the line, so replace them, e.g. with an underscore.

names(s)
 [1] "bioclim1"  "bioclim2"  "bioclim3"  "bioclim4"  "bioclim5"  "bioclim6" 
 [7] "bioclim7"  "bioclim8"  "bioclim9"  "bioclim10" "bioclim11" "bioclim12"
[13] "bioclim13" "bioclim14" "bioclim15" "bioclim16" "bioclim17" "bioclim18"
[19] "bioclim19"
names(s) <- c("Tmean", "Tdiurnal", "Isotherm", "Tseason", "Tmax_warmM",
              "Tmin_coldM", "Trange", "Tmean_wetQ", "Tmean_dryQ", "Tmean_warmQ",
              "Tmean_coldQ", "Pann", "P_wetM", "P_dryM", "Pseason",
              "P_wetQ", "P_dryQ", "P_warmQ", "P_coldQ")

Plot a map

Applying plot() to a multi-layer raster creates a panel plot where each layer is visualized in a separate subplot. Note, the argument nc specifies the number of columns of the panel plot. Here, we plot only the first four layers.

plot(s, 1:4, nc=2)

Above, we used numeric indices to select layers one to four. Alternatively, you can select the layers you want to plot by their names. The code below plots annual precipitation and the maximum temperature of the warmest month.

plot(s, c("Pann", "Tmax_warmM"))

ggplot2

The tidyterra package lets you plot SpatRaster objects with ggplot2. The function geom_spatraster() draws the raster layer you select with aes(fill = ...).

ggplot() +
  geom_spatraster(data = s, aes(fill = Tmean)) +
  scale_fill_viridis_c(name = "Tmean\n(°C x 10)", na.value = NA) +
  theme_minimal()

To plot multiple layers as a panel plot, pass a multi-layer SpatRaster without aes(fill = ...) and add facet_wrap(~lyr). All panels share one color scale, so combine only layers with the same unit, e.g. the temperature layers below.

ggplot() +
  geom_spatraster(data = s[[c("Tmin_coldM", "Tmean", "Tmax_warmM")]]) +
  facet_wrap(~lyr, ncol = 3) +
  scale_fill_viridis_c(name = "°C x 10", na.value = NA) +
  theme_minimal()

Write SpatRaster

Use writeRaster to write raster data. You must provide a SpatRaster and a filename. The file format will be guessed from the filename extension. If that does not work you can provide an argument like format=GTiff. Note the argument overwrite=TRUE and see ?writeRaster for more arguments, such as datatype= to set the a specific datatype (e.g., integer).

writeRaster(r, "test_output.tif", overwrite=TRUE)

Sampling

Raster can have millions of pixels, which can make computations very slow. So, sometimes it is useful to do calculations only on a sample of the raster pixels, e.g. for estimating mean and standard deviation of a raster, for building a statistical model. The spatSample function can be used to extract a random sample in different ways. For example, the random sample specified below yields a data.frame. If you want to retrieve the same random sample every time you re-run spatSample, set the random seed to the same number. This is helpful when debugging your code, and you want to exclude random variations during your testing. The argument na.rm=T excludes pixels with missing values (NA), e.g. ocean pixels, from the sample. Without it, rows that fall on NA pixels stay in the result and contain only NA values.

set.seed(42)
df <- spatSample(s, size=1000, method="random", na.rm=T)
head(df)
  Tmean Tdiurnal Isotherm Tseason Tmax_warmM Tmin_coldM Trange Tmean_wetQ
1   128       64      285    5478        246         23    222         78
2    93       67      294    5805        214        -14    227         30
3     6       64      197    9468        181       -148    327        132
4   114       93      303    7989        265        -42    306        197
5   127       84      378    5123        241         19    222         71
6    42       81      202   11878        248       -153    400        190
  Tmean_dryQ Tmean_warmQ Tmean_coldQ Pann P_wetM P_dryM Pseason P_wetQ P_dryQ
1        199         199          62 1378    217     34      52    589    117
2        119         167          18 1129    113     65      13    328    238
3        -60         132        -114  769    109     40      33    283    127
4         38         215           9  703     85     42      23    239    143
5        192         194          63 1372    141     83      17    403    266
6        -37         190        -113  497     60     27      23    159     85
  P_warmQ P_coldQ
1     133     525
2     280     310
3     283     145
4     221     144
5     270     368
6     159     103

You can also return a SpatVector object.

set.seed(42)
sv <- spatSample(s, size=1000, method="random", na.rm=T, as.points=T, as.df=F)

..or even a raster object when sampling in regular intervals.

set.seed(42)
sr <- spatSample(s, size=1000, method="regular", as.raster=T, as.df=F)
plot(sr, 1:2)

Predict

The terra package has two functions to make model predictions to (potentially very large) rasters. The function predict takes a multilayer raster and a fitted model as arguments. Fitted models can be of various classes, including lm, glm, gam, RandomForest, and prcomp (PCA). We’ve used predict already to apply linear models to data.frames. The function interpolate is similar but is for models that use coordinates as predictor variables, for example in Kriging and spline interpolation. Type this into the console to see the corresponding help page.

?`predict,SpatRaster-method`

References

Hijmans, R.J., 2026. Spatial data science with R and “terra.” URL https://rspatial.org/ (accessed 11.14.2026).
Hijmans, R.J., Brown, A., Barbosa, A.M., Cordano, E., Dyba, K., 2026. terra: Spatial data analysis. https://doi.org/10.32614/CRAN.package.terra