【问题标题】:Error in importing GeoTiff files - R RASTER package导入 GeoTiff 文件时出错 - R RASTER 包
【发布时间】:2016-07-12 15:23:20
【问题描述】:

我正在尝试创建一个循环,以便使用栅格{raster} 自动上传一些 GEOTiff 数据集。 首先,我使用变量path 定义了保存所有文件的文件夹。然后我在下面的代码中创建了一个循环,其中crop_name 是一个向量,其中包含我要导入的 GEOTiff 数据集名称的可变部分。

这是我正在使用的代码:

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

当我运行代码时,我收到以下错误消息:

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)

尽管如此,如果我尝试使用与生成并保存在path_2 中的文件相同的路径手动导入其中一个 GEOTiff 文件,我不会收到任何错误。 我读到有时 {raster} 包可能会给数据集名称中的下划线带来问题,但删除下划线并没有解决我的问题。我做错了什么?

【问题讨论】:

    标签: r error-handling r-raster geotiff


    【解决方案1】:

    这应该可以解决您的问题:

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

    您可以在此处使用栅格列表执行大量操作,例如 stacklapply 其他函数,或使用 for 循环为它们分配各自的名称。

    【讨论】:

    • 非常感谢您的有用评论!这确实简化了一切!
    【解决方案2】:

    使用assign 是个坏主意。相反,请使用列表并执行类似的操作

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

    但可能你想要的是:

    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)
    

    没有理由认为下划线很重要。

    【讨论】:

      猜你喜欢
      • 2015-05-08
      • 1970-01-01
      • 2014-08-21
      • 2022-12-27
      • 1970-01-01
      • 2021-11-28
      • 2019-01-01
      • 2020-07-29
      • 2011-09-21
      相关资源
      最近更新 更多