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)
}