Learn R Programming

fasterRaster

Faster raster processing in R using GRASS

fasterRaster is an R package designed specifically to handle large-in-memory/large-on-disk spatial rasters and vectors. fasterRaster does this using Open Source Geospatial's GRASS

fasterRaster was created with five design principles:

  • Value added: fasterRaster complements terra and sf, and is highly dependent on them! It is useful for analyzing large-in-memory/large-on-disk rasters and vectors that those packages struggle to handle. For medium- and small-size objects, terra and sf will almost always be faster.
  • Familiarity: If you know how to use terra, you basically know how to use fasterRaster! That's because most of the functions have the same name and almost the same arguments as terra functions.
  • Comparability: To the degree possible, outputs from fasterRaster are the same as those from functions in terra with the same name.
  • Simplicity: GRASS requires users to track things like "locations" or "projects", "mapsets", and "regions" for which there is no comparable analog in the terra or sf packages. fasterRaster handles these behind the scenes so you don't need to.
  • It's R: The rgrass package provides a powerful conduit through which you can run GRASS tools from R. As such, it provides much more flexibility than fasterRaster. However, to use rgrass, you need to know what GRASS tools you want to use and be familiar with GRASS syntax. fasterRaster obviates this step but uses rgrass as a backend, allowing you to focus on R syntax and look up help for functions the normal way you do in R. You don't need to know GRASS!

fasterRaster makes heavy use of the rgrass package by Roger Bivand and others, the terra package by Robert Hijmans, the sf package by Edzer Pebesma, Roger Bivand, and others, and of course GRASS, so is greatly indebted to all of these creators!

Vignettes & documentation

fasterRaster comes with four user-oriented vignettes, plus a pkgdown site with full documentation:

o Getting started (also reproduced below)
o Types of GRasters
o Making fasterRaster faster
o Addons
o Documentation

Installation

To install fasterRaster, please use:

install_packages('fasterRaster', dependencies = TRUE)

You can get the latest stable release using:

remotes::install_github('adamlilith/fasterRaster', dependencies = TRUE)

...and the development version from:

remotes::install_github('adamlilith/fasterRaster@intuitive_fasterRaster', dependencies = TRUE)

To use fasterRaster you must install GRASS version 8.3+ on your operating system. You will need to use the stand-alone installer, not the Open Source Geospatial (OS Geo) installer.

Optional: A few functions in fasterRaster require GRASS "addon" tools, which do not come bundled with GRASS. You do not need to install these addons if you do not use functions that call them. A list of functions that require addons can be seen in the "addons" vignette (in R, use vignette("addons", package = "fasterRaster")). This vignette also explains how to install addons.

An example

The example presented here is the same as that presented in the the "getting started" vignette.

We'll do a simple operation in which we:

  1. Add a buffer to lines representing rivers, then

  2. Calculate the distance to from each cell to the closest buffer and burn the distance values into a raster.

To do this, we'll be using maps representing the middle of the eastern coast of Madagascar. We will also use the terra and sf packages.

library(terra) # GIS for rasters and vectors
library(sf) # GIS for vectors
library(fasterRaster)

# Get example elevation raster and rivers vector:
madElev <- fastData('madElev') # SpatRaster with elevation
madRivers <- fastData('madRivers') # sp vector with rivers

# Plot inputs:
plot(madElev)
plot(st_geometry(madRivers), col = "lightblue", add = TRUE)

Before you use nearly any function in the package, you need to tell fasterRaster where GRASS is installed on your system. The installation folder will vary by operating system and maybe GRASS version, but will look something like this:

# Choose the appropriate one, and modify as needed:
grassDir <- "C:/Program Files/GRASS GIS 8.4" # Windows
grassDir <- "/Applications/GRASS-8.4.app/Contents/Resources" # Mac OS
grassDir <- "/usr/local/grass" # Linux

Now, use the faster() function to tell fasterRaster where GRASS is installed:

faster(grassDir = grassDir)

The fast() function is the key function for loading a raster or vector into fasterRaster format. Rasters in this package are called GRasters and vectors GVectors (the "G" stands for GRASS). We will now convert the madElev raster, which is a SpatRaster from the terra package, into a GRaster.

elev <- fast(madElev)
elev

You will see the GRasters metadata:

class       : GRaster
topology    : 2D 
dimensions  : 1024, 626, NA, 1 (nrow, ncol, ndepth, nlyr)
resolution  : 59.85157, 59.85157, NA (x, y, z)
extent      : 731581.552, 769048.635, 1024437.272, 1085725.279 (xmin, xmax, ymin, ymax)
coord ref.  : Tananarive (Paris) / Laborde Grid 
name(s)     : madElev 
datatype    : integer 
min. value  :       1 
max. value  :     570

Next, we'll do the same for the rivers vector. In this case, the vector is an sf object from the sf package, but we could also use a SpatVector from the terra package.

rivers <- fast(madRivers)
rivers
class       : GVector
geometry    : 2D lines 
dimensions  : 11, 11, 5 (geometries, sub-geometries, columns)
extent      : 731627.1, 762990.132, 1024541.235, 1085580.454 (xmin, xmax, ymin, ymax)
coord ref.  : Tananarive (Paris) / Laborde Grid 
names       :   F_CODE_DES          HYC_DESCRI      NAM   ISO     NAME_0 
type        :        <chr>               <chr>    <chr> <chr>      <chr> 
values      : River/Stream Perennial/Permanent MANANARA   MDG Madagascar 
              River/Stream Perennial/Permanent MANANARA   MDG Madagascar 
              River/Stream Perennial/Permanent      UNK   MDG Madagascar 
             ...and  8  more rows

Now, let's add a 1000-m buffer to the rivers using buffer(). As much as possible, fasterRaster functions have the same names and same arguments as their counterparts in the terra package to help users who are familiar with that package.

Note, though, that the output from fasterRaster is not necessarily guaranteed to be the same as output from the respective functions terra. This is because there are different methods to do the same thing, and the developers of GRASS may have chosen different methods than the developers of other GIS packages.

# width in meters because CRS is projected
river_buffers <- buffer(rivers, width = 1000)

Now, let's calculate the distances between the buffered areas and all cells on the raster map using distance().

dist_to_rivers_meters <- distance(elev, river_buffers)

Finally, let's plot the output.

plot(dist_to_rivers_meters)
plot(river_buffers, border = 'white', add = TRUE)
plot(rivers, col = "lightblue", add = TRUE)

And that's how it's done! You can do almost anything in fasterRaster you can do with terra. The examples above do not show the advantage of fasterRaster because the they do not use in large-in-memory/large-on-disk spatial datasets. For very large datasets, fasterRaster can be much faster! For example, for a large raster (many cells), the distance() function in terra can take many days to run and even crash R, whereas in fasterRaster, it could take just a few minutes or hours.

Exporting GRasters and GVectors from a GRASS session

You can convert a GRaster to a SpatRaster raster using rast():

terra_elev <- rast(elev)

To convert a GVector to the terra package's SpatVector, use vect():

terra_rivers <- vect(rivers)

You can use writeRaster() and writeVector() to save fasterRaster rasters and vectors directly to disk. This will always be faster than using rast() or vect() and then saving.

elev_temp_file <- tempfile(fileext = ".tif") # save as GeoTIFF
writeRaster(elev, elev_temp_file)

vect_temp_shp <- tempfile(fileext = ".shp") # save as shapefile
vect_temp_gpkg <- tempfile(fileext = ".gpkg") # save as GeoPackage
writeVector(rivers, vect_temp_shp)
writeVector(rivers, vect_temp_gpkg)

Versioning

fasterRaster versions will look something like 8.3.1.2, or more generally, M1.M2.S1.S2. Here, M1.M2 will mirror the version of GRASS for which fasterRaster was built and tested. For example, fasterRaster version 8.4.x.x will work using GRASS 8.4 (and version 8.3). The values in S1.S2 refer to "major" and "minor" versions of fasterRaster. That is, a change in the value of S1 (e.g., from x.x.1.0 to x.x.2.0) indicates changes that potentially break older code developed with a prior version of fasterRaster. A change in S2 refers to a bug fix, additional functionality in an existing function, or the addition of an entirely new function.

Note that the M1.M2 and S1.S2 increment independently. For example, if the version changes from 8.3.1.5 to 8.4.1.5, then the new version has been tested on GRASS 8.4, but code developed with version 8.3.1.x of fasterRaster should still work.

NOTE: While fasterRaster is still in beta/alpha release, the version will look something like 8.3.0.7XXX, following Hadley Wickham's guidelines for versioning under development.

Further reading

  • Robert Hijman's terra package and Edzer Pebesma's sf package are good places to start if you are not familiar with doing GIS in R.
  • Roger Bivand's rgrass package allows users to call any GRASS function with all of its functionality, which in some cases is far beyond what is allowed by fasterRaster.
  • The GRASS website is authoritative and contains the manual on all the GRASS functions used in this package and more.
  • The Wiki on how to run GRASS in R or R in GRASS will help you to become a power-user of GRASS in R.

Citation

A publication is forthcoming! In the meantime, please cite:

Smith, A.B. 2024. fasterRaster: Faster raster processing in R using GRASS. URL: https://cran.r-project.org/package=fasterRaster.

~ Adam

Copy Link

Version

Install

install.packages('fasterRaster')

Monthly Downloads

337

Version

8.4.1.0

License

GPL (>= 3)

Issues

Pull Requests

Stars

Forks

Maintainer

Adam B. Smith

Last Published

June 20th, 2025

Functions in fasterRaster (8.4.1.0)

Logic,GRaster,GRaster-method

Logic-methods operations on GRasters
Compare,GRaster,GRaster-method

Compare-methods operations on GRasters and GRegions
add<-

"Stack" a GRaster
GLocation-class

Classes for fasterRaster sessions, regions, rasters, and vectors
addCats,GRaster-method

Add rows or columns to the "levels" table of a categorical raster
activeCat,GRaster-method

Get or set the column with category labels in a categorical raster
Arith,GRaster,logical-method

Arithmetic operations on GRasters
addTable<-,GVector,data.frame-method

Attach or detach GVector's data table
aggregate,GRaster-method

Aggregate raster cells into larger cells or combine geometries of a vector
addons

Test if addons directory exists and if an addon is installed
as.int,GRaster-method

Coerce raster to integer, float, or double precision
as.contour,GRaster-method

Contour lines from a "GRaster"
bioclims,GRaster-method

BIOCLIM rasters
as.data.frame,GVector-method

Convert GVector to a data frame
as.lines,GRaster-method

Convert a raster to a lines vector
breakPolys,GVector-method

Fix issues with geometries of a vector
as.polygons,GRaster-method

Convert a raster to a polygons vector
as.points,GRaster-method

Convert a GRaster, or lines or polygons GVector to a points vector
app,GRaster-method

Apply a function to a set of rasters
appFunsTable

Functions that can be used in app()
combineLevels,GRaster-method

Combine levels table from multiple categorical GRasters
buffer,GRaster-method

Increase/decrease the size of a vector or around non-NA cells of a raster
catNames,GRaster-method

Names of columns of the levels table of a categorical raster
colbind,GVector-method

Add columns to the data table of a GVector
classify,GRaster-method

Classify GRaster cell values
c,GRaster-method

"Stack" GRasters
cellSize,GRaster-method

Area of GRaster cells
centroids,GVector-method

Centroid(s) of a vector or clumps in a raster
connectors,GVector,GVector-method

Create lines connecting nearest features of two GVectors
convHull,GVector-method

Minimum convex hull around a spatial vector
clump,GRaster-method

Group adjacent cells with similar values
compositeRGB,GRaster-method

Combine red, green, and blue color bands to make a composite GRaster
concats,GRaster-method

Combine values/categories of multiple GRasters into a single GRaster
clusterPoints,GVector-method

Identify clusters of points
complete.cases,GRaster-method

Rows of a GRaster or GVector's table that have no NAs or that have NAs
compareGeom,GRaster,GRaster-method

Determine if GRasters and/or GVectors are geographically comparable
crs,missing-method

Coordinate reference system of a GRaster or GVector
disagg,GVector-method

Coerce as multipart GVector to a singlepart GVector
.g.region

Call GRASS g.region tool
crop,GRaster-method

Remove parts of a GRaster or GVector
delaunay,GVector-method

Delaunay triangulation for points
datatype,GRaster-method

Get the datatype of a GRaster or of GVector columns
.plot

Plot using a G-object's sources() name
.projection

Get "GRASS" projection of raster or vector
.minVal

Get minimum value from GRaster metadata
.ext

Function to get extent from a "sources" name of a raster or vector
.makeGRaster

Create a GRaster
distance,GRaster,missing-method

Geographic distance
.g.proj

Call GRASS g.proj tool
crds,GRaster-method

Coordinates of a vector"s features or a raster"s cell centers
denoise,GRaster-method

Remove or retain "noise" in a raster using PCA
.copyGSpatial,GRaster-method

Make a copy of an object in GRASS
.makeSourceName

Make unique GRASS name for rasters, vectors, etc.
.backdoor

Setup fasterRaster for ABS
.nlevels

Count number of levels from a data.frame/table, list, or SpatRaster
.rename

Rename a raster or vector in an existing GRASS session
.rastInfo

Metadata on rasters and vectors in GRASS
.makeGVector

Create a GVector
.vectInfo

Metadata on a vector in GRASS
.vValidCats

Are the category values of a vector valid?
dropRows,data.table-method

Remove rows in a data.table, data.frame, or matrix.
erase,GVector,GVector-method

Select parts of a polygon GVector erase shared by another polygon GVector
.maxVal

Get maximum value from GRaster metadata
.exists,GRaster-method

Does the "GRASS" representation of a GRaster or GVector exist?
dim,GRegion-method

Number of rows, columns, depths, cells, and layers
.zonal

Internal function for zonal()
.layerIndex

Get index of raster layers
.geomtype

Get geometry type from the sources() name of a vector
droplevels,GRaster-method

Remove rows from the "levels" table of a categorical raster
.zonalByVector

Internal function for zonal() when y is a GVector
fillHoles,GVector-method

Fill holes in a GVector
fillNAs,GRaster-method

Fill NA cells in a raster using interpolation
expanse,GVector-method

Area of polygons or length of lines
extend,GRaster,numeric-method

Add rows and columns around a writeRaster
fast

Create a GRaster or GVector
ext,missing-method

Spatial bounds of a GRaster or GVector
extract,GRaster,GVector-method

Extract values from a GRaster at locations in a points GVector
fastData

Get one of the example rasters or spatial vectors
fasterRaster

"fasterRaster": Faster raster and spatial vector processing using "GRASS"
faster

Set or get options shared across fasterRaster functions
flow,GRaster-method

Identify watershed basins and direction and accumulation of flow
fractalRast,GRaster-method

Create fractal raster
fragmentation,SpatRaster-method

Landscape fragmentation class following Riitters et al. (2020)
focal,GRaster-method

Calculate cell values based on values of nearby cells
flowPath,GRaster-method

Path of water flow across a landscape
geomorphons,GRaster-method

Identify terrain feature types
geomtype,GVector-method

Geometry of a GVector (points, lines, or polygons)
mean,GRaster-method

Mathematical operations on two or more GRasters
global,GRaster-method

Summary statistics for GRasters
freq,GRaster-method

Frequencies of cell values in a raster
grid,GRaster-method

Create a grid GVector
grassGUI,missing-method

Start the GRASS GUI (potentially dangerous!)
grassStarted

Has "GRASS" been started or not?
hexagons,GRaster-method

Create a hexagonal grid
horizonHeight,GRaster-method

Horizon height
head,GVector-method

Return first or last part of the data frame of a GVector
grassInfo

GRASS citation, version, and copyright information
hillshade,GRaster-method

Hillshading
hist,GRaster-method

Plot a histogram of raster values
grassHelp

Open the help page for a GRASS tool
is.lonlat,character-method

Test if a coordinate reference system is unprojected
layerCor,GRaster-method

Correlation between GRasters
intersect,GVector,GVector-method

Intersection of two GVectors
kernel,GVector-method

Kernel density estimator of points
is.2d,GSpatial-method

Test if a GRaster or GVector is 2- or 3-dimensional
interpSplines,GVector,GRaster-method

Interpolate values at points to a GRaster using splines
levels,GRaster-method

Set and get categories for categorical rasters
.locationFind,missing-method

Match CRS of a GSpatial object and an existing "GRASS" location
.locationRestore,character-method

Revert to a previously-created "GRASS" "location"
madCoast

Shapefile of a portion of the coastline of Madagascar
is.int,GRaster-method

Data type of a raster
madCoast0

Spatial vector of a portion of the coastline of Madagascar
longlat,GRaster-method

Create longitude/latitude rasters
.location,GLocation-method

GRASS "location" of an object or the active session
.locationCreate,character-method

Connect to "GRASS"
madCover

Raster of land cover for an eastern portion of Madagascar
madDypsis

Spatial points vector of records of Dypsis in eastern Madagascar
madCoast4

Spatial vector of a portion of the coastline of Madagascar
madCoverCats

Table of land cover classes for an eastern portion of Madagascar
.locations

Meta-data on active GRASS locations
interpIDW,GVector,GRaster-method

Interpolate values at points to a GRaster using inverse-distance weighting
init,GRaster-method

GRaster with values equal to row, column, coordinate, regular, or "chess"
madForest2014

Forest cover in year 2014 for a portion of Madagascar
.ls

List objects in the active GRASS session
madChelsa

Rasters of bioclimatic variables for an eastern portion of Madagascar
madLANDSAT

Rasters of surface reflectance for an eastern portion of Madagascar
.mapset,GLocation-method

GRASS "mapset" of an object or the active session
minmax,GRaster-method

Minimum and maximum values or categories of a GRaster
madTmax

Rasters of average monthly maximum temperature for an eastern portion of Madagascar
madTmin

Rasters of average monthly minimum temperature for an eastern portion of Madagascar
madElev

Elevation raster for an eastern portion of Madagascar
.message

Display warning or message
ngeom,GVector-method

Number of geometries and subgeometries in a vector
mask,GRaster,GRaster-method

Mask values in a raster
nlevels,GRaster-method

Number of categories in a categorical raster
neighborhoodMatrix,GVector-method

Neighborhood matrix from a polygons GVector
is.na,GRaster-method

Mathematical operations on each layer of a GRasters
madForest2000

Forest cover in year 2000 for a portion of Madagascar
names,GRaster-method

Name(s) of a GRaster or columns of a GVector's data table
merge,GRaster,GRaster-method

Combine two or more rasters with different extents and fill in NAs
multivarEnvSim,GRaster,GRaster-method

Multivariate environmental similarity surface (MESS)
nacell,GRaster-method

Number of NA or non-NA cells in a raster
missingCats,GRaster-method

Values in a categorical raster with no assigned category
mow

Remove rasters and vectors from the GRASS cache
madRivers

Major rivers in a selected portion of Madagascar
match,GRaster-method

Find which cells of a GRaster match certain values
maskNA,GRaster-method

Mask all non-NA cells or all NA cells
pairs,GRaster-method

Scatterplot of values in each GRaster layer against the others
pcs

Retrieve a principal components model from a PCA GRaster
predict,GRaster-method

Make predictions from a linear or generalized linear model to a GRaster
rUnifRast,GRaster-method

Create a raster with random values drawn from a uniform distribution
madPpt

Rasters of average monthly precipitation for an eastern portion of Madagascar
princomp,GRaster-method

Apply a principal component analysis (PCA) to layers of a GRaster
plot,GRaster,missing-method

Display a raster or vector
plotRGB,GRaster-method

Create red-green-blue plot from a raster with RGB layers
rWalkRast,GRaster-method

Create raster representing one or more random walks
[<-

Replace values of a GRaster
project,GRaster-method

Change the coordinate reference system of a GRaster or GVector
[[<-

Replace layers of a GRaster
.quiet

Returns .quiet() or NULL for "flags" argument to GRASS modules
rast,GRaster-method

Convert a GRaster to a SpatRaster
rasterize,GVector,GRaster-method

Convert a GVector to a GRaster
replaceNAs,data.frame-method

Replace NAs in a data.table or data.frame column, or in a vector
$<-

Replace a raster layer or a column from a vector's data table
reorient,GRaster-method

Convert degrees between 'north-orientation' and 'east orientation'
rSpatialDepRast,GRaster-method

Create a random raster with or without spatial dependence
regress,GRaster,missing-method

Regression intercept, slope, r2, and t-value across each set of cells
rNormRast,GRaster-method

Create a raster with random values drawn from a normal distribution
res,missing-method

Spatial resolution
resample,GRaster,GRaster-method

Change the cell size of a GRaster
.rm

Delete objects in the active GRASS session
ruggedness,GRaster-method

Terrain ruggedness index
sampleRast,GRaster-method

Randomly sample cells from a GRaster
rvoronoi,GRaster-method

Create a randomly-positioned tesselation
.region,missing-method

Report or change the extent, dimensions, and/or resolution of a region GRASS
seqToSQL

Format a numeric series into an SQL value call
rbind,GVector-method

Combine one or more GVectors
selectRange,GRaster-method

Select values from rasters in a stack based on values in another raster
stretch,GRaster-method

Rescale values in a GRaster
streams,GRaster-method

Create stream network
scale,GRaster-method

Center and scale a GRaster, or the opposite
sources,GRaster-method

Name of a raster or vector in a GRASS session
segregate,GRaster-method

Create one GRaster layer per unique value in a GRaster
sineRast,GRaster-method

Sine wave rasters
smoothGeom,GVector-method

Smooth the geometry of a vector
subset,GRaster-method

Subset layers from a GRaster, or specific rows from a GVector
$

Subset a GRaster layer, or return values from a column of a GVector's table
print.rastInfo

Display a fasterRaster object
simplifyGeom,GVector-method

Simplify the geometry of a vector
terrain,GRaster-method

Slope, aspect, curvature, and partial slopes
spatSample,GRaster-method

Sample random points from a GRaster or GVector
thinPoints,GVector,GRaster-method

Reduce number of points in same raster cell
subst,GRaster-method

Replace a specific value(s) in a GRaster
[[

Subset layers from a GRaster, or specific columns from a GVector
trim,GRaster-method

Remove rows and columns from a raster that are all NA
topology,GSpatial-method

Topology (2- or 3-dimensions) of a GRaster or GVector
tiles,GRaster-method

Divide a GRaster into spatially exclusive subsets
[

Subset geometries of a GVector
sun

Solar radiance and irradiance
.vAttachDatabase

Add a database table to a GRASS attribute table
update,GRaster-method

Refresh metadata in a GRaster or GVector
union,GVector,GVector-method

Combine two GVectors
.vAsDataTable

Convert a GRASS vector's attribute table to a data.table
thinLines,GRaster-method

Reduce linear features on a raster so linear features are 1 cell wide
.vCats

Category column values of a GRASS vector
.vDetachDatabase

Add a database table to a GRASS attribute table
.vIncrementCats

Increment category values of a "GRASS" vector
.vHasDatabase

Tests if a GRASS vector is linked to an attribute table
vegIndex,GRaster-method

Vegetation indices from surface reflectance
xor,GVector,GVector-method

Select parts of polygons not shared between two GVectors
voronoi,GVector-method

Voronoi tessellation
vegIndices

vect,GVector-method

Convert a GVector to a SpatVector or sf vector
wetness,GRaster-method

Topographic wetness index
.vRecat

Re-make vector "category" (cat) values
.vNames

Names of columns of a GRASS vector's attribute table
.workDir,GLocation-method

Get a GLocation's working directory
zonalGeog,GRaster-method

Geographic statistics for sets of cells with the same values
zonal,GRaster,ANY-method

Statistics on cells of a GRaster stratified by cells of another raster
writeRaster,GRaster,character-method

Save a GRaster to disk
writeVector,GVector,character-method

Save a GVector to disk