0

ncdim_def来自 package的命令ncdf4旨在鼓励自动创建与尺寸相关的坐标变量,这是一个非常好的做法。

但是,它只允许为此坐标变量创建“双”或“整数”精度。由于外部原因,我需要将坐标变量“时间”写为浮点数。

为此,我使用以下结构,其中包括与尺寸定义分开创建坐标变量(即使用create_dimvar = FALSE文档中描述的选项ncdim_def

timevalue= seq(0.5,10.5)
VAR1value= seq(10.2,20.2)

# define time dim, but without the time var
timedim <- ncdim_def( name   = 'time'  ,
                  units  = '', 
                  vals   = seq(length(timevalue)),
                  unlim  = TRUE,
                  create_dimvar = FALSE)

# define time coordinate variable  
timevar <- ncvar_def(name  = 'time',
                 units = 'days since 1950-01-01 00:00:00',
                 dim = list(timedim), 
                 longname = 'time', 
                 prec = "float")

# define another variable
var1var<- ncvar_def(name = 'VAR1',
                units    = 'unit1',
                dim      = list(timedim),
                missval  = -9999.0, 
                longname = 'VAR1 long name')

defVar<-list(timevar,var1var)

# creating ncfile (removing any previous one for repeated attempt)
ncfname='test.nc'
if (file.exists(ncfname)) file.remove(ncfname)
ncout   <- nc_create(ncfname,defVar,force_v4=T, verbose = T)

# writing the values
ncvar_put(ncout,timevar,timevalue)
ncvar_put(ncout,var1var,VAR1value)

nc_close(ncout)

但是,这会返回错误:

"ncvar_put: warning: you asked to write 0 values, but the passed data array has 11 entries!"

实际上,生成的 netcdf 显示 (ncdump) :

dimensions:
    time = UNLIMITED ; // (0 currently)
variables:
    float time(time) ;
        time:units = "days since 1950-01-01 00:00:00" ;
    float VAR1(time) ;
        VAR1:units = "unit1" ;
        VAR1:_FillValue = -9999.f ;
        VAR1:long_name = "VAR1 long name" ;

我想我需要在创建时强制无限“时间”维度的维度,但我不明白如何在ncdf4.

4

1 回答 1

0

我遇到了同样的问题(需要时间维度作为浮点数而不是双精度数)并且能够通过将时间变量定义为具有我的小时向量长度的常规非无限维度来解决它

hours <- c("595377")
t <- ncdim_def("time", "", 1:length(hours), create_dimvar = FALSE)
timevar <- ncvar_def(name = "time",
                     units = 'hours since 1950-01-01 00:00:00',
                     dim = list(t),
                     longname = "time",
                     prec = "float")
variables <- list(timevar)
ncnew <- nc_create("TEST.nc", variables )
ncvar_put(ncnew, timevar, hours, start=c(1), count=c(length(hours)))
nc_close(ncnew)

不确定这是否仅在时间维度只有一个值时才有效...

于 2020-02-11T10:00:35.123 回答