我正在尝试使用栅格{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}包可能会在数据集名称中出现下划线问题,但删除下划线并不能解决我的问题。我做错了什么?
答案 0 :(得分:1)
使用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)
没有理由认为下划线很重要。
答案 1 :(得分:1)
这可以解决你的问题:
dir <- "Path to files"
files <- list.files(path = dir, pattern = ".tif")
rasters <- lapply(paste0(dir, files), raster)
您可以使用栅格列表执行大量操作,例如stack
,lapply
其他功能或使用for
循环为其分配各自的个人名称。