0

- I am beginner in R and I have made a script where I convert a .grd file into .tif file in a for loop (I have quite a lot of .grd files that should be converted). The script is as you can see below.


# Set your work directory    
setwd("xxx")  

library(rgdal)
library(sp)
library(raster)

# Data: .grd files in order to reproduce the code below
g1 <- raster(ncol=10, nrow=10)
vals <- 1:100
g1 <- setValues(g1, vals)
writeRaster(g1, filename="TEST_G1.grd", overwrite=TRUE) 

g2 <- raster(ncol=50, nrow=50)
vals <- 1
g2 <- setValues(g2, vals)
writeRaster(g2, filename="TEST_G2.grd", overwrite=TRUE) 

# Convert .grd to geotif in a for loop
rlist <- list.files(pattern=".grd$")
for (i in rlist)
{ 
  #Read raster
  x <- raster(rlist[i]) 
  #make new file name
  filename <- rlist[i]
  n <- unlist(strsplit(filename, split='.', fixed=TRUE))[1]
  name <- paste(n, ".tif", sep="")
  #write the raster as GTiff
  writeRaster(x, filename=name, format="GTiff", overwrite=TRUE) 
}

I have run all sentences in the script separately and managed to get geotif file. However, when I run the lobe I get the following error:

Error in .local(.Object, ...) :

Error in .rasterObjectFromFile(x, band = band, objecttype = "RasterLayer", : Cannot create a RasterLayer object from this file. (file does not exist)

The file does exist, and when I just run the last line separately the tif file is created... so I don't understand what is wrong with the loop. If I e.g. write "for (i in 1:2)" instead of "for (i in rlist)" it works. but I would prefer not to count the number of files in every directory, which is the reason I was trying to use "for (i in rlist)" Thanks a lot for you help!

Gro
  • 1
  • 2
  • 2
    Please read [How to make a great reproducible example in R?](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – M-- Jun 21 '17 at 16:04
  • Try printing i in every iteration: print(i). Once you get the error message, have a look what number i is and then start from there by examining and executing each line of code inside the loop for this particular i. I am sure you will find the error by doing this. We can't really help you better without a reproducible example. – maRtin Jun 22 '17 at 08:59
  • Thanks,- think the example should be reproducible now. – Gro Jun 23 '17 at 10:28

0 Answers0