Package stars provides infrastructure for data cubes, array data with labeled dimensions, with emphasis on arrays where some of the dimensions relate to time and/or space.

Spatial data cubes are arrays with one or more spatial dimensions. Raster data cubes have at least two spatial dimensions that form the raster tesselation. Vector data cubes have at least one spatial dimension that may for instance reflect a polygon tesselation, or a set of point locations. Conversions between the two (rasterization, polygonization) are provided. Vector data are represented by simple feature geometries (packages sf). Tidyverse methods are provided.

The stars package is loaded by

Spatiotemporal arrays are stored in objects of class stars; methods for class stars currently available are

(tidyverse methods are only visible after loading package tidyverse).

Reading a satellite image

We can read a satellite image through GDAL, e.g. from a GeoTIFF file in the package:

tif = system.file("tif/L7_ETMs.tif", package = "stars")
x = read_stars(tif)

We see that the image is geographically referenced (has coordinate values along axes), and that the object returned (x) has three dimensions called x, y and band, and has one attribute.

Each dimension has a name; the meaning of the fields of a single dimension are:

field meaning
from the origin index (1)
to the final index (dim(x)[i])
offset the start value for this dimension (pixel boundary), if regular
delta the step (pixel, cell) size for this dimension, if regular
refsys the reference system, or proj4string
point logical; whether cells refer to points, or intervals
values the sequence of values for this dimension (e.g., geometries), if irregular

This means that for an index i (starting at \(i=1\)) along a certain dimension, the corresponding dimension value (coordinate, time) is \(\mbox{offset} + (i-1) \times \mbox{delta}\). This value then refers to the start (edge) of the cell or interval; in order to get the interval middle or cell centre, one needs to add half an offset.

Dimension band is a simple sequence from 1 to 6. Since bands refer to colors, one could put their wavelength values in the values field.

For this particular dataset (and most other raster datasets), we see that offset for dimension y is negative: this means that consecutive array values have decreasing \(y\) values: cell indexes increase from top to bottom, in the direction opposite to the \(y\) axis.

read_stars reads all bands from a raster dataset, or optionally a subset of raster datasets, into a single stars array structure. While doing so, raster values (often UINT8 or UINT16) are converted to double (numeric) values, and scaled back to their original values if needed if the file encodes the scaling parameters.

The data structure stars is a generalisation of the tbl_cube found in dplyr; we can convert to that by

but this will cause a loss of certain properties (cell size, reference system, vector geometries)

Switching attributes to dimensions and back

We see that the newly created dimension lost its name, and the single attribute got a default name. We can set attribute names with setNames, and dimension names and values with st_set_dimensions:


Besides the tidyverse subsetting and selection operators explained in this vignette, we can also use [ and [[.

Since stars objects are a list of arrays with a metadata table describing dimensions, list extraction (and assignment) works as expected:

At this level, we can work with array objects directly.

The stars subset operator [ works a bit different: its

  • first argument selects attributes
  • second argument selects the first dimension
  • third argument selects the second dimension, etc


selects the second attribute, the first 10 columns (x-coordinate), all rows, and bands 2-4.

Alternatively, when [ is given a single argument of class sf, sfc or bbox, [ will work as a crop operator:

circle = st_sfc(st_buffer(st_point(c(293749.5, 9115745)), 400), crs = st_crs(x))
plot(x[circle][, , , 1], reset = FALSE)
plot(circle, col = NA, border = 'red', add = TRUE, lwd = 2)


We can read rasters at a lower resolution when they contain so-called overviews. For this GeoTIFF file, they were created with the gdaladdo utility, in particular

gdaladdo -r average L7_ETMs.tif  2 4 8 16

which adds coarse resolution versions by using the average resampling method to compute values based on blocks of pixels. These can be read by

x1 = read_stars(tif, options = c("OVERVIEW_LEVEL=1"))
x2 = read_stars(tif, options = c("OVERVIEW_LEVEL=2"))
x3 = read_stars(tif, options = c("OVERVIEW_LEVEL=3"))
par(mfrow = c(1, 3), mar = rep(0.2, 4))

Reading a raster time series: NetCDF

Another example is when we read raster time series model outputs in a NetCDF file, e.g. by

system.file("nc/", package = "stars") %>%
    read_stars("data/") -> w
## pr, tas,

We see that

For this dataset we can see that

  • variables have units associated (and a wrong unit, C is assigned to temperature)
  • time is now a dimension, with proper units and time steps

Alternatively, this dataset can be read using read_ncdf, as in

which doesn’t convert time values in a proper R time format.

Reading datasets from multiple files

Model data are often spread across many files. An example of a 0.25 degree grid, global daily sea surface temperature product is found here; a subset of the 1981 data was downloaded from here.

We read the data by giving read_stars a vector with character names:

Next, we select sea surface temperature (sst), and drop the singular zlev (depth) dimension using adrop:

z <- y %>% select(sst) %>% adrop()

We can now graph the sea surface temperature (SST) using ggplot, which needs data in a long table form, and without units:

## Loading required package: viridisLite
ggplot() +  
  geom_stars(data = z[1], alpha = 0.8, downsample = c(10, 10, 1)) + 
  facet_wrap("time") +
  scale_fill_viridis() +
  coord_equal() +
  theme_map() +
  theme(legend.position = "bottom") +
  theme(legend.key.width = unit(2, "cm"))

Writing stars objects to disk

We can write a stars object to disk by using write_stars; this used the GDAL write engine. Writing NetCDF files without going through the GDAL interface is currently not supported. write_stars currently writes only a single attribute:

write_stars(adrop(y[1]), "sst.tif")

See the explanation of merge above to see how multiple attributes can be merged (folded) into a dimension.

Cropping a raster’s extent

Using a curvilinear grid, taken from the example of read_ncdf:

We can now crop the grid to those cells falling in

nc = st_transform(nc, st_crs(prec_slice)) # datum transformation
plot(prec_slice[nc], border = NA, breaks = qu_0_omit(prec_slice[[1]]), reset = FALSE)
## although coordinates are longitude/latitude, st_intersects assumes that they are planar
plot(st_geometry(nc), add = TRUE, reset = FALSE, col = NA, border = 'red')

The selection prec_slice[nc] essentially calls st_crop(prec_slice, nc) to get a cropped selection. What happened here is that all cells not intersecting with North Carolina (sea) are set to NA values. For regular grids, the extent of the resulting stars object is also be reduced (cropped) by default; this can be controlled with the crop parameter to st_crop and [.stars.

Vector data cube example

Like tbl_cube, stars arrays have no limits to the number of dimensions they handle. An example is the origin-destination (OD) matrix, by time and travel mode.

OD: space x space x travel mode x time x time

We create a 5-dimensional matrix of traffic between regions, by day, by time of day, and by travel mode. Having day and time of day each as dimension is an advantage when we want to compute patterns over the day, for a certain period.

nc = st_read(system.file("gpkg/nc.gpkg", package="sf")) 
## Reading layer `nc.gpkg' from data source `/usr/local/lib/R/site-library/sf/gpkg/nc.gpkg' using driver `GPKG'
## Simple feature collection with 100 features and 14 fields
## geometry type:  MULTIPOLYGON
## dimension:      XY
## bbox:           xmin: -84.32385 ymin: 33.88199 xmax: -75.45698 ymax: 36.58965
## epsg (SRID):    4267
## proj4string:    +proj=longlat +datum=NAD27 +no_defs
to = from = st_geometry(nc) # 100 polygons: O and D regions
mode = c("car", "bike", "foot") # travel mode
day = 1:100 # arbitrary
## udunits system database from /usr/share/xml/udunits
units(day) = as_units("days since 2015-01-01")
hour = set_units(0:23, h) # hour of day
dims = st_dimensions(origin = from, destination = to, mode = mode, day = day, hour = hour)
(n = dim(dims))
##      origin destination        mode         day        hour 
##         100         100           3         100          24
traffic = array(rpois(prod(n), 10), dim = n) # simulated traffic counts
(st = st_as_stars(list(traffic = traffic),  dimensions = dims))
## stars object with 5 dimensions and 1 attribute
## attribute(s), summary of first 1e+05 cells:
##     traffic     
##  Min.   : 0.00  
##  1st Qu.: 8.00  
##  Median :10.00  
##  Mean   :10.01  
##  3rd Qu.:12.00  
##  Max.   :26.00  
## dimension(s):
##             from  to                      offset                       delta
## origin         1 100                          NA                          NA
## destination    1 100                          NA                          NA
## mode           1   3                          NA                          NA
## day            1 100 1 [(days since 2015-01-01)] 1 [(days since 2015-01-01)]
## hour           1  24                       0 [h]                       1 [h]
##                                   refsys point
## origin      +proj=longlat +datum=NAD2... FALSE
## destination +proj=longlat +datum=NAD2... FALSE
## mode                                  NA FALSE
## day                              udunits FALSE
## hour                             udunits FALSE
##                                                                        values
## origin      MULTIPOLYGON (((-81.47276 3...,...,MULTIPOLYGON (((-78.65572 3...
## destination MULTIPOLYGON (((-81.47276 3...,...,MULTIPOLYGON (((-78.65572 3...
## mode                                                             car,...,foot
## day                                                                      NULL
## hour                                                                     NULL

This array contains the simple feature geometries of origin and destination so that we can directly plot every slice without additional table joins. If we want to represent such an array as a tbl_cube, the simple feature geometry dimensions need to be replaced by indexes:

The following demonstrates how dplyr can filter bike travel, and compute mean bike traffic by hour of day:

b <- st %>% 
  as.tbl_cube() %>%
  filter(mode == "bike") %>%
  group_by(hour) %>%
  summarise(traffic = mean(traffic)) %>%
require(ggforce) # for plotting a units variable
## Loading required package: ggforce
ggplot() +  
  geom_line(data = b, aes(x = hour, y = traffic))