Learn R Programming

terra (version 1.6-47)

roll: Rolling (moving) functions

Description

Compute "rolling" or "moving" functions, such as the "rolling average"

Usage

# S4 method for SpatRaster
roll(x, n, fun=mean, type="around", circular=FALSE, na.rm=FALSE, filename="", ...) 

# S4 method for numeric roll(x, n, fun=mean, type="around", circular=FALSE, na.rm=FALSE)

Value

Same as x

Arguments

x

SpatRaster or numeric

n

integer > 1. The size of the "window", that is, the number of sequential elements to use in the fun. This is normally an odd number

fun

a function like mean, min, max, sum

type

character. One of "around", "to", or "from". The choice indicates which values should be used in the computation. The focal element is always used. If type is "around", the other elements are before and after the focal element. Alternatively, you can select the elements preceding the focal element ("to") or those coming after it "from". For example, when using n=3 for element 5 of a vector; "around" used elements 4,5,6; "to" used elements 3,4,5, and "from" uses elements 5,6,7

circular

logical. If TRUE, the data are considered to have a circular nature (e.g. days or months of the year), such that there are no missing values before first or after the last value.

na.rm

logical. If TRUE, NA values should be ignored (by fun)

filename

character. Output filename

...

additional arguments for writing files as in writeRaster

See Also

Examples

Run this code
## numeric
roll(1:12, 3, mean)
roll(1:12, 3, mean, "to")
roll(1:12, 3, mean, circular=TRUE)

## SpatVector
r <- rast(ncol=2, nrow=2, nlyr=10, vals=1)
r[1,2] = 2
r[2,2] = 4

roll(r, n=3, "sum", "from", na.rm=FALSE) |> values()
roll(r, n=3, "sum", "from", na.rm=TRUE) |> values()
roll(r, n=3, "sum", "from", circular=TRUE) |> values()

roll(r, n=3, "sum", "to", na.rm=TRUE) |> values()

roll(r, n=3, "sum", "around", circular=TRUE) |> values()

Run the code above in your browser using DataLab