Learn R Programming

enmSdmX (version 1.2.12)

squareCellRast: Create a raster with square cells

Description

This function creates a raster from an object with an extent (i.e., another raster or similar spatial object) with square cells. The user can specify cell resolution (linear dimension) or the approximate number of cells desired.

Usage

squareCellRast(x, numCells = NULL, res = NULL, vals = NULL)

Value

SpatRaster object. The raster will have an extent of the same size or larger than the extent of x.

Arguments

x

An object with a spatial extent property (e.g., a SpatRaster or a SpatVector).

numCells

Positive integer, approximate number of cells desired. If this is specified, then res is ignored. If this number of cells cannot be fit into the desired extent exactly, then the actual number of cells will be larger.

res

Positive numeric. Size of a cell in the units of the projection of x (typically meters). Ignored if numCells is not NULL.

vals

Numeric, value to assign to cells. Note that if this is shorter than the number of cells in the output, then values will be recycled. If longer, then values will be truncated. The default is to assign all 0s.

Examples

Run this code

library(sf)
library(terra)

# project outline of Madagascar to equal-area:
data(mad0)
mad0Ea <- st_transform(mad0, getCRS('madAlbers'))

n <- 101
cellSize_meters <- 10E4
byNumCells <- squareCellRast(mad0Ea, numCells=n)
byCellSize <- squareCellRast(mad0Ea, res=cellSize_meters)

oldPar <- par(mfrow=c(1, 2))

main1 <- paste0('Cells: ', n, ' desired, ', ncell(byNumCells), ' actual')
plot(byNumCells, main = main1)
plot(mad0Ea, add = TRUE)

main2 <- paste0('Cells ', cellSize_meters, ' m on a side')
plot(byCellSize, main = main2)
plot(mad0Ea, add = TRUE)

par(oldPar)

# Note that in this example they look the same, but the one on the left
# has one less row than the one on the right.

Run the code above in your browser using DataLab