rr-rasterparallel-foreach

Keeping raster names in a foreach loop


I am running a focal function on a large raster stack and would like to speed up the process with foreach. I am able to output the rasters correctly with the below code, however the newly created rasterstack gives the name "layer" to each of the rasters when I want them to keep the names of the original input rasters.

Usually in a standard for loop I just rename the rasters with the names function but I cant seem to get it to work on foreach.

Have provided my code below with some randomly generated rasters.

library(dplyr)
library(doParallel)
library(foreach)
library(raster)
library(rgdal)
library(plyr)

#random raster data
r1 <- raster(nrows = 100, ncols = 100, res = 0.1, xmn = -1.5, xmx = 1.5, ymn = -1.5, ymx = 1.5, vals = 1)
rr <- lapply(1:3, function(i) setValues(r1,runif(ncell(r1))))

# stack and name rasters
rr=stack(rr)
names(rr) = c('name1', 'name2', 'name3')

# Initiate cluster
cl = makeCluster(detectCores() -1)
registerDoParallel(cl)

# foreach loop through raster stack
foreach_test = foreach(rasname=iter(names(rr)),.packages = c("dplyr", "raster", "rgdal", "plyr")) %dopar%{
  raster::focal(rr[[rasname]], w=matrix(1, nrow=3,ncol=3), fun = cv, na.rm = TRUE)
}

stopCluster(cl)

To be clear, I would like the output rasters of the foreach loop to keep the raster names as "name1","name2" & "name3".

Thanks in advance!


Solution

  • You can simply re-assign the names at the end.

    library(foreach)
    library(raster)
    
    r1 <- raster(nrows = 100, ncols = 100, res = 0.1, xmn = -1.5, xmx = 1.5, ymn = -1.5, ymx = 1.5)
    set.seed(0)
    rr <- lapply(1:3, function(i) setValues(r1,runif(ncell(r1)))) |> stack()
    names(rr) = c('name1', 'name2', 'name3')
    
    test <- foreach(i=1:nlayers(rr),.packages ="raster") %do%{
      raster::focal(rr[[i]], w=matrix(1, nrow=3,ncol=3), fun = cv, na.rm = TRUE)
    }
    
    x <- stack(test)
    names(x) <- names(rr)
    
    x
    #class      : RasterStack 
    #dimensions : 30, 30, 900, 3  (nrow, ncol, ncell, nlayers)
    #resolution : 0.1, 0.1  (x, y)
    #extent     : -1.5, 1.5, -1.5, 1.5  (xmin, xmax, ymin, ymax)
    #crs        : +proj=longlat +datum=WGS84 +no_defs 
    #names      :     name1,     name2,     name3 
    #min values :  18.58546,  12.54229,  21.75082 
    #max values :  99.30544, 142.98081, 136.98756