简体   繁体   中英

Error in importing GeoTiff files - R RASTER package

I am trying to create a loop for automatically upload some GEOTiff datasets using the raster{raster}. Firstly, I defined the folder where all my files are saved using the variable path . Then I created a loop as in the code below, where crop_name is a vector containing the variable part of the names of the GEOTiff datasets that I want to import.

This is the code that I am using:

path <- file.path("C:","Users","pbarbieri","Documents","Pietro","R Analysis", "Budgets test countries baseline scenario", "global", "crop prodution", "All")

for (i in 1:length(crop_name)){

  name_file_upload <-paste(crop_name[i],"_Production.tif",sep = "")
  path_2 <- file.path(path, name_file_upload)
  name_file <- paste(crop_name[i], "production", sep = "_")
  assign(name_file,  raster(path_2))   
}

When I run the code, I get the following error message:

Error in .local(.Object, ...) : 
   `C:\Users\pbarbieri\Documents\Pietro\R Analysis\Budgets test countries baseline scenario\global\crop prodution\All\barley_Production.tif' does not exist in the file system,
   and is not recognised as a supported dataset name.

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

Nevertheless, if I try to import manually one of the GEOTiff files using the same path as the one generated and saved in path_2 , I don't get any error. I read that sometime the {raster} package might give problems with underscores in the datasets names, but deleting the underscores did not solve my problem. What am I doing wrong?

Using assign is a bad idea. Instead, use a list and do something like

x <- list()
for () {
    x[[i]] <- raster(path_2)
}

But probably what you want is:

path <- file.path("C:/Users/pbarbieri/Documents/Pietro/R Analysis/Budgets test countries baseline scenario/global/crop prodution/All", 
     paste0(crop_name,"_Production.tif"))
s <- stack(x)

There is no reason to think underscores matter.

This should solve your problems:

   dir <- "Path to files"
   files <- list.files(path = dir, pattern = ".tif")
   rasters <- lapply(paste0(dir, files), raster)

You can do a ton of things here with the list of rasters such as stack , lapply other functions across them or use a for loop to assign them their own individual names.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM