如何使用 for 循环在 [r] 中加载多个栅格?

How do you load multiple rasters in [r] using a for loop?

我正在尝试使用引用列表的循环加载 144 个光栅 (.tif),但 运行 出错了。请注意,我的目录中只有这 144 个 .tif 文件,并且每个文件名的某些部分都是唯一的。我不确定如何最好地为此创建一个可重现性最低的示例,因此我缩写了目录和文件名。

首先我加载了 "raster" 包并设置了我的工作目录, 然后我还设置了一个变量 'path' 等于我的工作目录。 接下来,我在目录

中创建了一个文件列表
setwd("T:/sample/geotiffs")
path<-"T:/sample/geotiffs"
rastlist <- list.files(path=path, pattern='tif$', full.names=TRUE)

我尝试使用之前 post 中的语法编写我的代码:File not found in R raster loop

for (jj in 1:length(mget(rastlist)))  {
  x[jj] <- raster(paste0(rastlist[jj]))
}

但是,我收到以下有关缺少第一个文件的错误消息: "Error: value for ‘T:/sample/geotiffs/geotiff1.tif’ not found"

我也试过在没有 mget() 和 paste0() 的情况下以这种方式编码,

x<-vector(mode="logical",length=144)
for(i in 1:length(rastlist))  {
  x[i]<-raster(rastlist[i])
}

但是,我收到了 50 多个警告“1: In x[i] <- raster(rastlist[i]) : 要替换的项目数不是替换长度的倍数

有什么想法吗?在我 运行 这段代码之后,我的向量 x 似乎是一个包含 144 个随机整数的向量,我不确定为什么 - 也许我需要一种更好的方法来启动长度等于的空白向量 'x'我的名单?

你试过了吗:

x <- purrr:map(rastlist, raster)

这应该有效:

library(raster)
f <- list.files(path=path, pattern='tif$', full.names=TRUE)
r <- lapply(f, raster)

如果栅格具有相同的范围和分辨率,您可能想要改为执行此操作

s <- stack(f)