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!
You can simply re-assign the names at the end.