【问题标题】:Is there a way to check if a variable exists in a netcdf file already in R?有没有办法检查 R 中已经存在的 netcdf 文件中是否存在变量?
【发布时间】:2021-10-06 09:38:07
【问题描述】:

我创建了一个包含许多变量的 NetCDF 文件。在调试和测试将新变量写入文件时,我在某些文件中创建了变量“RH”,但大多数文件中仍然没有“RH”。现在我想运行我的脚本,它将循环遍历我的所有文件并将数据放入它存在的 RH 变量中,或者只添加变量,然后添加数据,它不存在的地方。

library(ncdf4)
#Open the original file with my variables in it
ncid_old <- nc_open("original.nc"), write=TRUE )
#Create the 'RH' variable and put it in the file
var <- ncvar_def( 'RH', '%', list(xdim2,ydim2,tdim2), mv2 )
ncid_old <- ncvar_add( ncid_old, var)

如果变量已经存在(在某些情况下也是如此),我会收到此错误:

Error in R_nc4_def_var_float: NetCDF: String match to name in use
Name of variable that the error occurred on: "RH"
I.e., you are trying to add a variable with that name to the file, but it ALREADY has a variable with that name!

如何首先检查变量“RH”是否存在?然后我可以在我的 r 脚本中包含一个 if 语句来检查它是否存在,如果它已经存在,那么我不包含该行:

ncid_old <- ncvar_add( ncid_old, var)

我只是直接将数据添加到变量中:

ncvar_put( ncid_old, var, RHdata, start=c(1,1,1), count=c(nx,ny,12))

【问题讨论】:

    标签: r netcdf ncdf4


    【解决方案1】:
    "RH" %in% names(ncid_old$var)
    

    【讨论】:

      猜你喜欢
      • 2022-11-12
      • 2020-10-19
      • 2016-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多