使用多个变量在R中创建netcdf

时间:2014-06-12 14:36:47

标签: r

我想创建一个包含11个或更多不同变量的netcdf。为此,我试图在一个循环中写它,但它不起作用。我的代码就是这样的:

#Defining names and dimensions
 nam_cwt  <-  c("N","NE","E","SE","S","SW","W","NW","C","A","U") #number of variables
 CWTvar   <- paste("var_",nam_cwt,sep="")
 data_cwt <- list()
 mat_cwt  <- array()

 dimX <- dim.def.ncdf("longitude", "degrees_east", Longvector)
 dimY <- dim.def.ncdf("latitude", "degrees_north", Latvector)
 dimT  <- dim.def.ncdf("time","days since 1961-01-01",1:length(my.date), unlim=TRUE)
 missval  <- -999

#Creating and filling the netcdf file

for (i in 1:length(nam_cwt)){

  #Getting every matrix of elements
data_cwt <- lapply(cwt_out,function(x) x[[1]][[i]][[2]])
dmatrix  <- unlist(data_cwt)
mat_cwt  <- array(dmatrix,dim=c(144,length(my.date),25))
tmat_cwt <- aperm(mat_cwt,c(1,3,2))

CWTvar[[i]] <- var.def.ncdf(nam_cwt[i],"days",list(dimX,dimY,dimT),                                        ,missval,longname=nam_cwt[i])
 ncfile <- create.ncdf("nctypes.nc",CWTvar)
 put.var.ncdf(ncfile,CWTvar[i],tmat_cwt)


 }

问题是我不确定是否应该使用var.add.ncdf(而不是put.var.ncdf)。 关于那个???的任何想法 如何在循环中创建和编写文件?

任何帮助都会有所帮助!

1 个答案:

答案 0 :(得分:2)

以下是我将如何做到这一点:首先使用其中一个变量创建一个netcdf文件,然后在循环中添加并填充其他变量。

library(ncdf)
#Defining names and dimensions
nam_cwt  <-  c("N","NE","E","SE","S","SW","W","NW","C","A","U") #number of variables
CWTvar   <- paste("var_",nam_cwt,sep="")

# values and length of dimensions
Longvector = -180:180
Latvector = -90:90
Datevector   = 1:10
x= length(Longvector)
y= length(Latvector)
z= length(Datevector)

# define dimensions
dimX <- dim.def.ncdf("longitude", "degrees_east", Longvector)
dimY <- dim.def.ncdf("latitude", "degrees_north", Latvector)
dimT  <- dim.def.ncdf("time","days since 1961-01-01",1:length(Datevector), unlim=TRUE)

# set missing value
missval  <- -9999

# create the file with first variable so dimensions are set
CWTvar1 <- var.def.ncdf(name=nam_cwt[1],"days",list(dimX,dimY,dimT), missval=missval)
ncfile <- create.ncdf("nctypes.nc",vars=CWTvar1)

# open newly created file for writing data
mync = open.ncdf(con='nctypes.nc', write=T)

# create some data for first variable
mydata = array(data=runif(n=x*y*z, min=0, max=10), dim=c(x,y,z))

# add data to ncdf file
put.var.ncdf(nc=mync, varid='N', vals=mydata)

# now add all other variables with the same dimensions
for (i in 2:length(nam_cwt)){

    # generate new data
    mydata = array(data=runif(n=x*y*z, min=0, max=10)*i, dim=c(x,y,z))  
    # create new variable
    CWTvar <- var.def.ncdf(name=nam_cwt[i],"days",list(dimX,dimY,dimT) ,missval=missval)
    # add new variable to existing file
    mync = var.add.ncdf(nc=mync, v=CWTvar)
    # add data to variable in file
    put.var.ncdf(nc=mync,varid=CWTvar$name,vals=mydata)


}

close.ncdf(mync)

# check file
newnc = open.ncdf(con='nctypes.nc')
par(mfrow=c(4,3))
for (i in 1:length(nam_cwt)){
    zz = get.var.ncdf(newnc, varid=nam_cwt[i])
    image(x=Longvector, y=Latvector, z=zz[,,1])
}
close.ncdf(newnc)