0

I have a netcdf raster object with multiple layers (time: 30 years * 12 month = 360 steps).

The raster is constituted of multiple grid-cells (say 1000). I want to linearly detrend each month separately and each grid cell separately to obtain a residual raster object with same dimensions as the input.

For a long format data frame with columns [x,y,value,month,year], I would do it this way:

library(tidyverse)
data %>%
group_by(x, y, month) %>%
      nest() %>%
      mutate(model_trend = map(data,  ~ lm(value ~ year, data = .))) %>%
      mutate(augment_trend  = map(model_trend,  ~ broom::augment(.))) %>%
      unnest(cols = c(augment_trend)) %>%
      ungroup() %>%
      dplyr::select(x, y, year, month, .resid)

I am sure there are much more efficient and similarly easy ways of doing this operation using spatial packages such as terra, stars and so forth.

How do I do that?

2

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.