【发布时间】:2016-12-14 15:35:43
【问题描述】:
我需要读取大量的.asc 文件,删除行并将它们转换为stack() 的光栅堆栈。压缩包数据的来源在这里:ftp://ftp.dwd.de/pub/CDC/grids_germany/monthly/radiation_global/
我已经解压缩了文件。但是现在我写的这段代码真的很慢,我的电脑无法完成:
files <- list.files("mydirectory", pattern="\\.asc$",
full.names=TRUE, recursive=TRUE)
i <- lapply(files, readLines) #read data
i <- lapply(i, function(x){x[-(1:28)]}) #delete rows
i <- lapply(i, function(x){gsub('-999', ' NA ', x, fixed = TRUE)}) #convert '-999' to NA
i <- lapply(i, function(x){scan(textConnection(x), what = double(), n = 866*654)}) #convert to numeric
i <- lapply(i, function(x){matrix(x, nrow = 866, ncol = 654, byrow = TRUE)}) #convert to matrix
r <- lapply(i, function(x){raster(x)}) #rasterize data
st <- stack(r) #convert to stack-raster
我想知道是否有更好的方法将此数据转换为光栅文件。其他 .asc 文件只有 6 行作为标题,如下所示:ftp://ftp.dwd.de/pub/CDC/grids_germany/monthly/precipitation/01_Jan/。我通过一个更简单的函数读取该数据,该函数仅使用stack()-函数:
loadRaster <- function(directory, output, clipping){
files <- list.files(path=directory, pattern="\\.asc$",
full.names=TRUE, recursive=TRUE)
stc <- stack(files)
crs(stc) <- gk3
stcC <- crop(stc, extent(clipping))
writeRaster(stcC, filename=output)
}
#You can ignore the code below "stc <-stack(files)"
【问题讨论】:
-
你说它很慢,但瓶颈在哪里?将
system.time()添加到您的所有lapply呼叫以查看有问题的呼叫。它将帮助我们确定我们的帮助。此外,lapply 通常可以通过library(parallel)和函数parLapply来加速并行化。它可能会有所帮助。
标签: r raster large-files