如何使用for循环在[r]中加载多个栅格? [英] How do you load multiple rasters in [r] using a for loop?

查看:248
本文介绍了如何使用for循环在[r]中加载多个栅格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用引用列表的循环加载144个栅格(.tif),但遇到错误.请注意,我的目录中仅包含这144个.tif文件,并且每个文件名的某些部分都是唯一的.我不确定如何最好地为此创建一个最小的可复制示例,因此我已经缩写了目录和文件名.

I am trying to load 144 rasters (.tif) using a loop that refers to lists, but running into errors. Note that my directory only has these 144 .tif files in it, and there are portions of each filename that are unique. I'm not sure how to best create a minimally reproducible example for this, so I've abbreviated directories and file names.

首先,我加载了光栅"包并设置了我的工作目录, 然后我还要设置一个等于工作目录的变量路径". 接下来,我在目录中创建了文件列表

first I loaded "raster" package and set my working directory, then I also set a variable 'path' equal to my working directory. Next, I created a list of the files in the directory

setwd("T:/sample/geotiffs")
path<-"T:/sample/geotiffs"
rastlist <- list.files(path=path, pattern='tif$', full.names=TRUE)

我试图用上一篇文章中的语法编写代码:文件不在R光栅循环中找到

I tried to write my code with syntax from a previous post: File not found in R raster loop

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

但是,关于缺少第一个文件,我收到以下错误消息: 错误:找不到'T:/sample/geotiffs/geotiff1.tif'的值"

However, I got the following error about missing the first file: "Error: value for ‘T:/sample/geotiffs/geotiff1.tif’ not found"

我还尝试了在没有mget()和paste0()的情况下以这种方式进行编码,

I also tried coding it this way without the mget() and paste0(),

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

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

However, I am getting 50+ warnings "1: In x[i] <- raster(rastlist[i]) : number of items to replace is not a multiple of replacement length"

有什么想法吗?运行此代码后,我的向量x似乎是带有144个随机整数的向量,我不确定为什么-也许我需要一种更好的方法来启动长度等于我的栅格列表的空白向量'x'?

Any ideas? After I run this code my vector, x, seems to be a vector with 144 random integers and I am not sure why - perhaps I need a better way to initiate a blank vector 'x' with length equal to my rastlist?

推荐答案

这应该有效:

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

如果栅格具有相同的范围和分辨率,则可能需要这样做

If the rasters have the same extent and resolution, you might want to do this instead

s <- stack(f)

这篇关于如何使用for循环在[r]中加载多个栅格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆