【问题标题】:Read large number of .asc-files, delete rows and save as raster in R读取大量 .asc 文件,删除行并在 R 中另存为栅格
【发布时间】: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


【解决方案1】:

最后我通过逐步使用textConnection()(再次打开和关闭)得到了它,因为——这可能是缓慢的原因——打开的连接有一个限制。

files <- list.files(path="mydirectory", pattern="\\.asc$", 
                    full.names=TRUE, recursive=TRUE)
i <- lapply(files, readLines)
i <- lapply(i, function(x){x[-(1:28)]})
i <- lapply(i, function(x){gsub('-999', ' NA ', x, fixed = TRUE)})
names(i) <- substr(files, 92,97)
i1 <- lapply(i[1:100], function(x){scan(textConnection(x), what = double(), n = 866*654)})
closeAllConnections()
i2 <- lapply(i[101:200], function(x){scan(textConnection(x), what = double(), n = 866*654)})
closeAllConnections()
i3 <- lapply(i[201:300], function(x){scan(textConnection(x), what = double(), n = 866*654)})
closeAllConnections()
i4 <- lapply(i[301:length(i)], function(x){scan(textConnection(x), what = double(), n = 866*654)})
closeAllConnections()
i <- c(i1, i2, i3, i4)
m <- lapply(i, function(x){matrix(x, nrow = 866, ncol = 654, byrow = TRUE)})
r <- lapply(m, function(x){raster(x)})
stc <- stack(r)

【讨论】:

    猜你喜欢
    • 2019-10-07
    • 2016-07-28
    • 2022-06-16
    • 2014-05-21
    • 2015-09-13
    • 2020-05-09
    • 1970-01-01
    • 1970-01-01
    • 2014-11-12
    相关资源
    最近更新 更多