我正在尝试创建一个包含120个光栅文件的光栅堆栈。我在循环中生成这些文件,并将生成的栅格添加到rasterstack。代码如下:
library(raster)
stack_P_95 <- stack()
for (i in startyear:endyear)
{
file <- paste(indir,"\\prec_",i,".nc",sep="")
command <- paste("cdo timmin ",file," ",workdir,"min.nc",sep="")
system(command)
command <- paste("cdo timmax ",file," ",workdir,"max.nc",sep="")
system(command)
command <- paste("cdo timpctl,95 ",file," ",workdir,"min.nc
",workdir,"max.nc ",workdir,"P95_",i,".nc",sep="")
system(command)
grid <- raster(paste(workdir,"P95_",i,".nc",sep=""))
stack_P_95 <- stack(stack_P_95,grid)
}
crs(stack_P_95) <- "+proj=utm +zone=45 +ellps=WGS84 +datum=WGS84 +units=m
+no_defs"
writeRaster(stack_P_95,paste(outdir,model,"_P95.nc",sep=""),format="CDF",overwrite=T)
但我正在创建的stack_P_95只有最后一个栅格重复n次(endyear -startyear)次。
这个问题的可能原因是什么? 在此过程中不会产生任何错误或警告。
我添加了输入文件和最终输出的链接: Input files
答案 0 :(得分:0)
试试此代码
r <- list() # create list objects
for (i in startyear:endyear)
{
r[i] <- raster(paste(workdir,"temp_",i,".nc",sep=""))
}
rs <- stack(r) # create raster stack from list object
答案 1 :(得分:0)
您的代码没有任何问题。
创建一些示例栅格:
> library(raster)
Loading required package: sp
> for(i in 2001:2005){ r = raster(matrix(i,10,10)); writeRaster(r,paste0("temp_",i,".nc"))}
Loading required namespace: ncdf4
这让我:
$ ls
temp_2001.nc temp_2002.nc temp_2003.nc temp_2004.nc temp_2005.nc
所有这些都不同:
$ gdalinfo temp_2004.nc | grep max
layer#max=2004
max=2004
$ gdalinfo temp_2001.nc | grep max
layer#max=2001
max=2001
现在在一个干净的R会话中我运行你的代码:
library(raster)
workdir="./"
stack_1 <- stack()
startyear = 2001
endyear = 2004
for (i in startyear:endyear)
{
tempnc <- raster(paste(workdir,"temp_",i,".nc",sep=""))
stack_1 <- stack(stack_1,tempnc)
}
我得到一个有四个不同层的堆栈:
> range(stack_1[[1]][])
[1] 2001 2001
> range(stack_1[[2]][])
[1] 2002 2002
> range(stack_1[[3]][])
[1] 2003 2003
与您的代码不同,我的代码完全可以重现。如果您在干净的R环境中运行我的代码,并且所有图层都是&#34; 2004&#34;然后你的系统出现了严重错误。如果图层与我的图层相同,那么您的文件或您未向我们展示的代码就会出现问题。