Search code examples
rloopsrasterterra

Dividing 2 rasterstacks in a loop


I have two folders. One folder containing historical climate and another folder containing future climate. Each folder has 9 GCM models. I am trying to divide GCM of future by corresponding GCM of historical to get change. Since I do not want to repeat the task by dividing 9 times, I am trying to use for loop. Below is my code

hist_pr <- list.files("./CMIP6 data/Main data/CMIP6 
analysis/Historical/Normal", pattern = "^pr.*\\.nc$", full.names = TRUE)
fut_pr <- list.files("./CMIP6 data/Main data/CMIP6 analysis/Future/2020- 
2049/SSP126/Normal/", pattern = "^pr.*\\.nc", full.names = TRUE)

for (i in 1: length(hist_pr)){
   hist_stack <- terra::rast(hist_pr[i])

for (j in 1:length(fut_pr)) {
  fut_stack <- terra::rast(fut_pr[[j]])

change <- fut_stack/hist_stack

fn <- paste0("./Tests/", sub("_historical_.*\\.nc", 
"_2020_2049_ssp126_anomaly.nc", basename(hist_pr[i])))
terra::writeCDF(change, filename = fn, overwrite=T)

}
}

I get this error: "Error: [/] extents do not match". 

I was expecting I will get 9 raster layers (GCMs) of "change". I have been trying to solve this problem but somehow I am not able to do. Could anyone help me on this? I remain highly thankful!


Solution

  • You can do something like this

    hist_pr <- list.files("Normal", pattern = "^pr.*\\.nc$", full.names = TRUE)
    fut_pr <- list.files("Future/2020-2049/SSP126/Normal/", pattern = "^pr.*\\.nc", full.names = TRUE)
    fn <- paste0("./Tests/", sub("_historical_.*\\.nc", "_2020_2049_ssp126_anomaly.nc", basename(hist_pr)))
    
    for (i in seq_along(hist_pr)) {
        his <- terra::rast(hist_pr[i])
        fut <- terra::rast(fut_pr[i])
        change <- fut / his
        terra::writeCDF(change, filename=fn[i], overwrite=T)
    }