Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save names of raster produced in loop with different names in R

Tags:

loops

r

raster

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

like image 290
user53020 Avatar asked Nov 27 '25 21:11

user53020


2 Answers

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)
}               
like image 73
Robert Hijmans Avatar answered Nov 29 '25 11:11

Robert Hijmans


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="")
like image 31
mobiusklein Avatar answered Nov 29 '25 10:11

mobiusklein



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!