【发布时间】:2016-10-03 20:36:16
【问题描述】:
我有几个包含 700 多个二进制编码栅格的目录,我将每个目录的输出栅格取平均值。但是,我目前在 for 循环中逐个创建栅格,然后将新创建的栅格加载回 R 以获取总和以获得每月降雨总量。
但是,由于我不需要单个栅格,只需要平均栅格,我有一种预感,我可以在 1 个循环中完成这一切,而不是保存栅格,而只保存输出平均栅格,但我要来了简述如何在 R 中编程。
setwd("~/Desktop/CMORPH/Levant-Clip/200001")
dir.output <- '~/Desktop/CMORPH/Levant-Clip/200001' ### change as needed to give output location
path <- list.files("~/Desktop/CMORPH/MonthlyCMORPH/200001",pattern="*.bz2", full.names=T, recursive=T)
for (i in 1:length(path)) {
files = bzfile(path[i], "rb")
data <- readBin(files,what="double",endian = "little", n = 4948*1649, size=4) #Mode of the vector to be read
data[data == -999] <- NA #covert missing data from -999(CMORPH notation) to NAs
y<-matrix((data=data), ncol=1649, nrow=4948)
r <- raster(y)
e <- extent(-180, 180, -90, 83.6236) ### choose the extent based on the netcdf file info
tr <- t(r) #transpose
re <- setExtent(tr,extent(e)) ### set the extent to the raster
ry <- flip(re, direction = 'y')
projection(ry) <- "+proj=longlat +datum=WGS84 +ellps=WGS84"
C_Lev <- crop(ry, Levant) ### Clip to Levant
M_C_Lev<-mask(C_Lev, Levant)
writeRaster(M_C_Lev, paste(dir.output, basename(path[i]), sep = ''), format = 'GTiff', overwrite = T) ###the basename allows the file to be named the same as the original
}
#
raspath <- list.files ('~/Desktop/CMORPH/Levant-Clip/200001',pattern="*.tif", full.names=T, recursive=T)
rasstk <- stack(raspath)
sum200001<-sum(rasstk)
writeRaster(avg200001, paste(dir.output, basename(path[i]), sep = ''), format = 'GTiff', overwrite = T) ###the basename allows the file to be named the same as the original
目前,执行此代码大约需要 75 分钟,而且我还有大约 120 个目录要走,并且正在寻找更快的解决方案。
感谢所有和任何 cmets 和输入。最好的,埃文
【问题讨论】:
-
在我看来,编写栅格似乎不是必需的,因为堆栈也接受输入中的栅格对象列表。因此,您可以将 writeraster 替换为按顺序将 M_C_lev 分配给列表的元素。但是,这可能会占用大量内存。此外,如果您确定所有 rastet 的范围相同,请考虑在堆栈中使用“快速”选项。
-
另外,我似乎记得'brick'可能比'stack'更快
标签: r for-loop raster r-raster