I have a RasterStack with 3 layers each one of them containing 19 variables. Using writeRaster I need to save specific variables into my directory while naming the saved files with the actual variable name and it's respective layer id.

If one were to take the variables one by one in each layer...

writeRaster(myRasterStack$var1.1,  "var1.1.grd", format = "raster")

var1 indicating the actual name of the variable in the raster object and .1 it's respective layer.

I'm working on the following loop.

variables <- as.factor(c("var1.1", "var8.1", "var1.2", "var8.2","var1.3", "var8.3"))
for (i in 1:length(variables))
  writeRaster(myRasterStack$[i], filename = paste0("variables", i,"/data/.grd"), format = "raster")

What am I missing in the loop?

2 Answers 2


The problem is how to access each layer inside the loop. myRasterStack$var1.1 works fine for a simple call, but in a loop is better to access as myRasterStack[[1]] (and also I agree the issue name). So use:

for (i in 1:length(variables)) {
  writeRaster(myRasterStack[[i]], filename = paste0("/data/",variables[i],".grd"), format = "raster")
  • That solved my problem. While naming the outputted file, any suggestion in how to proceed to add a complement to the "var1.grd" filename. Say I want to name It "modelA-var1.grd". Aug 9, 2018 at 13:19
  • Just add what you want to into paste0, as paste0("/data/ModelA-",variables[i],".grd"). I suggest you to replace dot in names, is better to use underline, like: as.factor(c("var1_1", "var8_1", "var1_2", "var8_2","var1_3", "var8_3"))
    – aldo_tapia
    Aug 9, 2018 at 13:22
  • Solved. I hope this post serve as help to someone else. Aug 9, 2018 at 13:23
  • @MiltonAlves great!
    – aldo_tapia
    Aug 9, 2018 at 13:30

It looks to me that your path is sorted in the wrong order. Try:

for(i in 1:length(variables))) writeRaster(myRasterStack[i], filename = paste0("data/", variables[i],".grd"), format = "raster")

or whatever your folderstrukture looks like.

  • actually in "variables" my intention was to use the name in the ith position of my vector object variables. Thats not indicating where my variables are. Thy are in the object myRasterStack. In "./data/.grd" I want to inform where my file is to be saved. Aug 9, 2018 at 12:31
  • sry, I dont get it. in the 'filename =' slot in writeRaster command you have to deliver the exact filename. To paste this together looks like the right approach to me. So if you want to use the ith item of variables it would look like paste0("data/",variables[i],".grd"). Which produces fro the first element 'data/var1.1.grd'. or you can use my eddited code which is a little shorter.
    – Julian
    Aug 9, 2018 at 12:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.