简体   繁体   中英

R - Extracting all variables of ncdf4 file into separate variable names

I am opening a.netcdf file and want to extract all variables into their own variable names using a non-repetitive method.

Currently I can do this using the following

#route of file we want to open
fn <- "grid_T_19800105.nc"

#opens netCDF file
nc <- nc_open(fn)

#Extracts latitude and longitude matrices into variables
nav_lat <- ncvar_get(nc,"nav_lat")
nav_long <- ncvar_get(nc,"nav_lon")

#Extracts depth levels
depth <- ncvar_get(nc,"deptht")

#Extracts Temperature
votemper <- ncvar_get(nc,"votemper")

#Extracts Salinity
vosaline <- ncvar_get(nc,"vosaline")

#Extracts sea surface height
sossheig <- ncvar_get(nc,"sossheig")

#Extracts ice fraction
soicecov <- ncvar_get(nc,"soicecov")

#Close ncdf file to avoid memory loss
nc_close(nc)

But there seems to be a much faster way of doing this. Currently I am trying

#route of file we want to open
fn <- "grid_T_19800105.nc"

#opens netCDF file
nc <- nc_open(fn)

variables <- names(nc$var)

apply(variables,ncvar_get)

But this returns the error

Error in match.fun(FUN): argument "FUN" is missing, with no default

A possible solution is to use a for loop:

for(i in 1:length(variables)) {
    assign(variables[i], ncvar_get(nc, variables[i]))
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM