Dor*_*thy 4 tiff r raster spatial lapply
我是 R 新手,尤其是在空间数据方面。我试图找到一种方法将多个 (~600) 单波段光栅 (.tif) 文件有效地导入到 R 中,所有文件都存储在同一文件夹中。不确定这是否重要,但请注意,在我的 Mac 和 Windows Parallel VM 上的文件夹中查看时,每个 .tif = .TIF 都有以下五 (5) 种文件格式;.tfw; .TIF.aux.xml; .TIF.ovr; .TIF.xml。无论如何,以下代码(以及我尝试过的其他类似变体)似乎不起作用:
library(sp)
library(rgdal)
library(raster)
#path to where all .tif files are located
setwd("/path/to/workingdirectory")
#my attempt to create a list of my .tif files for lapply
temp = list.files(pattern="*.tif")
temp #returns 'character(0)'
#trying to use the raster function to read all .tif files
myfiles = lapply(temp, raster)
myfiles #returns 'list()'
Run Code Online (Sandbox Code Playgroud)
有没有办法使用某种形式的循环来有效地导入所有光栅文件?
小智 6
如果栅格具有相同的范围,您可以简单地将它们加载到堆栈中
#first import all files in a single folder as a list
rastlist <- list.files(path = "/path/to/wd", pattern='.TIF$', all.files=TRUE, full.names=FALSE)
library(raster)
allrasters <- stack(rastlist)
Run Code Online (Sandbox Code Playgroud)
我找到了答案,并将发布完整代码以帮助遇到此问题的其他初学者 R 用户。要调用列表元素,请使用双方括号 [[]],如下所示:
#first import all files in a single folder as a list
rastlist <- list.files(path = "/path/to/wd", pattern='.TIF$',
all.files=TRUE, full.names=FALSE)
#import all raster files in folder using lapply
allrasters <- lapply(rastlist, raster)
#to check the index numbers of all imported raster list elements
allrasters
#call single raster element
allrasters[[1]]
#to run a function on an individual raster e.g., plot
plot(allrasters[[1]])
Run Code Online (Sandbox Code Playgroud)
嘘。感谢冻糕的帮助。
好的,我认为以下代码有效:
rastlist <- list.files(path = "/path/to/wd", pattern='.TIF$', all.files=TRUE,
full.names=FALSE)
lapply(rastlist, raster)
Run Code Online (Sandbox Code Playgroud)
但现在如何访问单个光栅文件以进行进一步分析?