Assuming that I need to calculate the variance of the raster data for the same longitude, Is using the sapp
function the right way to go? But I failed.
I can now use the more complex method of converting to data.frame and grouping to calculate the variance:
library(terra)
library(tidyverse)
r <- rast(nrows = 5, ncols = 10, vals = c(1:50))
plot(r)
r |>
terra::as.data.frame(xy= TRUE) |>
group_by(x) |>
summarise(lonsd = sd(lyr.1))
Is there a more straightforward function in terra
? Please tell me if you know.
There are also more complex scenarios where this needs to be done on multiple layers of raster data at the same time, how should this be done?
You can use aggregate to compute something for each column (or row) in a raster
Example data
library(terra)
set.seed(1)
r <- rast(nrows = 5, ncols = 10, vals = sample(100), nlyr=2)
Solution
a <- aggregate(r, c(nrow(r), 1), var, na.rm=TRUE)
data.frame(lon=xFromCol(r), values(a))
# lon lyr.1 lyr.2
#1 -162 468.2 1364.3
#2 -126 1007.3 493.0
#3 -90 557.5 822.2
#4 -54 358.3 1089.7
#5 -18 1224.3 665.7
#6 18 1125.3 260.3
#7 54 1180.3 207.2
#8 90 631.3 433.0
#9 126 1564.7 1669.7
#10 162 881.7 752.3
Or
a <- as.data.frame(r, xy=TRUE)
aggregate(a[,3:4], a["x"], var, na.rm=TRUE)