I am trying to create 5 raster files and write each raster file with a separate name. So far, I have managed to achieve this:
c=5
for (i in 1:c){
z<-RFsimulate(x=x,y=y,grid=TRUE,model = model,maxGB=4.0)
a<-raster(z)
projection(a) <- "+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0"
writeRaster(raster(a),filename="raster[i].tif")
}
But I find only one raster file (raster 1) in my working directory. I thought I will have five raster files names raster1, raster2.....raster5. Could anyone help me what's wrong with my code?
Thanks
This is a very basic R question. You should probably practice a bit with simple loops. Use print statements to see what is going on. Note that you create object a but you do not use it. "raster[i].tif" is a string, it has no relation to iterator i. Here is a solution:
n <- 5
for (i in 1:n){
z <- RFsimulate(x=x,y=y,grid=TRUE,model = model,maxGB=4.0)
a <- raster(z, crs="+proj=longlat +datum=WGS84")
f <- paste0('raster', i, '.tif')
writeRaster(a, filename=f)
}
R does not have automatic string interpolation. If you want to put the value of i into the filename string, you'll need to explicitly substitute it. Instead try this:
...
projection(a) <- ...
filename <- gsub("INDEX", i, "raster_INDEX.tif")
writeRaster(raster(z), filename=filename
}
This code uses the gsub function to substitute the token "INDEX" in a passed string with the value of i, and returns the modified string.
You could alternatively construct the file name with paste
filename <- paste("raster_", i, ".tif", sep="")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With