如何将多个“.asc”光栅文件读入 R

How to read multiple ".asc" raster files into R

我正在尝试将多个光栅文件读入 R,以便将它们合并为一个更大的光栅。大多数文件是 ASCII 文件,但有些也是 TIF 文件。

我试过来自 how to efficiently import multiple raster (.tif) files into R 但总是收到错误消息。我不认为这与我的文件有关,因为我可以一次读取一个单独的光栅并将它们很好地合并。我最终要处理数百个栅格,所以需要一种方法来一次处理它们!

我的示例数据位于文件夹“HowesValley”中,该文件夹是我工作目录中的一个子文件夹。

当我输入:

rastlist <- list.files(path = "/HowesValley", pattern='.asc', all.files=TRUE, full.names=FALSE)
allrasters <- stack(rastlist)

我收到错误消息

Error in x[[1]] : subscript out of bounds

我也试过:

rastlist <- list.files(path = "/HowesValley", pattern='.asc', all.files=TRUE, full.names=FALSE)
allrasters <- lapply(rastlist, raster)

当我输入

allrasters[[1]]

我明白了

Error in allrasters[[1]] : subscript out of bounds

当我输入

plot(allrasters[[1]])

我明白了

Error in h(simpleError(msg, call)) : error in evaluating the argument 'x' in selecting a method for function 'plot': subscript out of bounds

有什么想法吗?

回答我自己的问题,因为我找到了一种有效的方法,以防其他人遇到同样的麻烦!

我从 https://www.r-bloggers.com/2014/04/merge-asc-grids-with-r/ and How to select multiple files with different extension in filelist in R

找到了我需要的代码

适用于我的代码是:

library(rgdal)  
library(raster) 
setwd("D:/HowesValley") #set the working directory to the folder of interest
f <-list.files(path = ".",pattern = '.*\.(tif|asc)$') #search for both .tif and .asc files
r <- lapply(f, raster) 
x <- do.call("merge",r) 
plot(x)
writeRaster(x,"HowesValleyComb.asc")