简体   繁体   English

导入GeoTiff文件时出错-R RASTER软件包

[英]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}. 我正在尝试创建一个循环,以使用raster {raster}自动上传一些GEOTiff数据集。 Firstly, I defined the folder where all my files are saved using the variable path . 首先,我使用变量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. 然后,按照下面的代码创建一个循环,其中crop_name是一个向量,其中包含要导入的GEOTiff数据集名称的可变部分。

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. 不过,如果我尝试导入使用的生成并保存在一个相同的路径的GeoTIFF文件手动一个path_2 ,我没有得到任何错误。 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. 我读到,有时{raster}软件包可能会给数据集名称中的下划线带来问题,但是删除下划线并不能解决我的问题。 What am I doing wrong? 我究竟做错了什么?

Using assign is a bad idea. 使用assign是一个坏主意。 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. 你可以在这里做一吨的事情光栅如清单stacklapply等功能跨越,或用for循环分配他们自己个人的名字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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