我正在尝试根据较短的时间周期在foor循环中将8个netcdf文件子集(其中一个是here),然后将它们另存为新的netcdf文件。
我看到其他人已经问过如何根据不同的时间段(here或here)对netcdf文件进行子集化,但是一旦在netcdf文件上进行操作,“ for循环”就会继续没有完成就运行(甚至没有第一个netcdf文件),我也不知道为什么。
这是我使用的代码:
library(raster)
library(netcdf4)
library(lubridate)
#setting wd=indir containing netcdf files
setwd(indir)
files=list.files(pattern="nc")
for (j in seq_along(files)){
#setting wd containing netcdf files in the loop
setwd(indir)
b<-brick(files[j])
nc<-nc_open(files[j])
#variable
varname<-names(nc[['var']][3])
varunits <- ncatt_get(nc,varname,"units")[[2]]
lon<-ncvar_get(nc,"lon")
lat<-ncvar_get(nc,"lat", verbose = F)
time<-ncvar_get(nc, "time")
tunits <- ncatt_get(nc, "time", "units")[[2]]
dlname <- ncatt_get(nc, varname,"long_name")[[2]]
nc_close(nc)
#assigning a crs
proj4string(b)<-"+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0"
#setting time as.Date
tm<-ymd(getZ(b))
#setting time to rasterBrick
b<-setZ(b, tm)
# subsetting
b2<-subset(b, which(tm < as.Date('2006-01-01')))
#setting wd where I want to save the "new" netcdf files
setwd(outdir)
writeRaster(b2, filename = paste0(varname, "_1971_2006_Noce.nc"),
format="CDF", varname=varname, varunit=varunits, longname=dlname,
xname="lon", yname="lat", zname="time", zunit=tunits, overwrite=TRUE)
}
非常感谢您提供有关如何使循环正常工作的帮助!