Search code examples
rrasterterra

Calculate row-wise or column-wise means using R terra functions


I'm trying to calculate row or column means of a SpatRaster/SpatRaster stack using the R terra package in order to make a Hovmoller plot, but am finding myself stumped.

I'd typically just use something like this:

# Test matrix

A = matrix(seq(1,6,1),4,3,byrow = TRUE)

# Usually lots of NAs in the data

A[c(2,4,5)] <- NA

# Calculate the mean of each row

m = apply(A, 1, "mean", na.rm =T)

How would someone calculate this using terra functions? Reading the documentation for the various app() functions it doesn't seem apparent how to calculate values based on SpatRaster dimensions. Hopefully I'm missing something obvious.


Solution

  • You can use aggregate

    This

    x <- rast(A)
    aggregate(x, c(1, ncol(x)), mean, na.rm=TRUE) |> values()
    #     lyr.1
    #[1,]   2.0
    #[2,]   5.5
    #[3,]   2.0
    #[4,]   5.5
    

    Returns the same numbers as

    apply(A, 1, "mean", na.rm =T)
    #[1] 2.0 5.5 2.0 5.5