如何获得具有特定维度的 netCDF 变量列表?
How can I get a list of netCDF variables with particular dimensions?
{
dimensions:
grp = 50 ;
time = UNLIMITED ; // (0 currently)
depth = 3 ;
scalar = 1 ;
spectral_bands = 2 ;
x1AndTime = 13041 ;
x2AndTime = 13041 ;
midTotoAndTime = 13041 ;
variables:
double time(time) ;
double a1(time, hru) ;
double a2(time, hru) ;
double a3(x1AndTime, hru) ;
double a4(x2AndTime, hru) ;
double a5(hru) ;
打开 R
中的 netCDF 文件
out <- ncdf4::nc_open('test.nc')
获取所有变量
ncvars <- names(out[['var']])
这为我提供了 netCDF 文件中 所有 变量的列表。
如何获得维度为 time
和 hru
的变量列表?
预期输出:
列表 a1, a2
注意:这是 python,不是 R 但说明了逻辑。
import netCDF4
out = netCDF4.Dataset("test.nc")
# list of vars w dimenions 'time' and 'hru'
wanted_vars = []
# loop thru all the variables
for v in out.variables:
# this is the name of the variable.
print v
# variable.dimensions is a tuple of the dimension names for the variable
# In R you might need just ('time', 'hru')
if out.variables[v].dimensions == (u'time', u'hru'):
wanted_vars.append(v)
print wanted_vars
nc <- ncdf4::nc_open("/some/nc/file.nc")
for (vi in seq_along(nc$var)) { # for all vars of nc file
dimnames_of_var <- sapply(nc$var[[vi]]$dim, "[[", "name")
message(length(nc$var[[vi]]$dim), " dims of var ", names(nc$var)[vi], ": ",
paste(dimnames_of_var, collapse=", "))
if (all(!is.na(match(dimnames_of_var, c("hru", "time"))))) { # order doesnt matter
message("variable ", names(nc$var)[vi], " has the wanted dims!")
}
}
{
dimensions:
grp = 50 ;
time = UNLIMITED ; // (0 currently)
depth = 3 ;
scalar = 1 ;
spectral_bands = 2 ;
x1AndTime = 13041 ;
x2AndTime = 13041 ;
midTotoAndTime = 13041 ;
variables:
double time(time) ;
double a1(time, hru) ;
double a2(time, hru) ;
double a3(x1AndTime, hru) ;
double a4(x2AndTime, hru) ;
double a5(hru) ;
打开 R
out <- ncdf4::nc_open('test.nc')
获取所有变量
ncvars <- names(out[['var']])
这为我提供了 netCDF 文件中 所有 变量的列表。
如何获得维度为 time
和 hru
的变量列表?
预期输出:
列表 a1, a2
注意:这是 python,不是 R 但说明了逻辑。
import netCDF4
out = netCDF4.Dataset("test.nc")
# list of vars w dimenions 'time' and 'hru'
wanted_vars = []
# loop thru all the variables
for v in out.variables:
# this is the name of the variable.
print v
# variable.dimensions is a tuple of the dimension names for the variable
# In R you might need just ('time', 'hru')
if out.variables[v].dimensions == (u'time', u'hru'):
wanted_vars.append(v)
print wanted_vars
nc <- ncdf4::nc_open("/some/nc/file.nc")
for (vi in seq_along(nc$var)) { # for all vars of nc file
dimnames_of_var <- sapply(nc$var[[vi]]$dim, "[[", "name")
message(length(nc$var[[vi]]$dim), " dims of var ", names(nc$var)[vi], ": ",
paste(dimnames_of_var, collapse=", "))
if (all(!is.na(match(dimnames_of_var, c("hru", "time"))))) { # order doesnt matter
message("variable ", names(nc$var)[vi], " has the wanted dims!")
}
}