I have a RasterStack object from witch I need to take some layers into a new RasterStack. To to that I've created a loop. My problem in that I am losing my original layers names in the process. As you will see below, when I take just one of the layers without the loop, the original name are kept.
In addition I also need to group the layers (variables) into models, so I can iterate though the variables inside each model with a bigger loop I'm building.
How do I extract layers from a raster keeping the original layer naming?
Here is some exemple..
## stk1 is the original RasterStack
## stk1 has 3 models in it (.1,.2,.3) each model has 4 variables (day1, day2, day3, day 4)
names(stk1)
[1] "day1.1" "day2.1" "day3.1" "day4.1"
[5] "day1.2" "day2.2" "day3.2" "day4.2"
[9] "day1.3" "day2.3" "day3.3" "day4.3"
Here is the loop i've got running.
## Selecting day2 and day4 from stk1
variables <- as.factor(c("day2.1", "day4.1",
"day2.2", "day4.2",
"day2.3", "day4.3"))
for (i in 1:length(variables))
{
writeRaster(stk1[[i]], filename = paste0("./data/stk1-", variables[i], ".grd"), format = "raster", bylayer = TRUE) # I've tried with and without bylayer.
}
stk1_select <- stack(list.files("./data/", pattern = ".grd$", full.names = TRUE))
names(stk1_select) **# this names should be exactly as it is in variables**
[1] "day3.1" "day1.1"
[5] "day2.1" "day4.1"
[9] "day4.2" "day2.2"
Extracting one by one does keep the original layer name.
writeRaster(stk1[["day2.1"]], filename = paste0("./data/stk-", "day2.1", ".grd"), format = "raster")
day2.1 <- raster("./data/stk-day2.1.grd")
names(day2.1)
[1] "day2.1"
Finally what I need is like an array of rasters. stk1_select should be modelA( var: day2, day4), modelB (var: da2, day4), modelC (day2, day4)