1

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

Fish_Person
  • 107
  • 5
  • 1
    Consider reading `?apply`. This function needs at least 3 arguments to be specified, and you seem to be supplying only two. – xilliam Jan 03 '23 at 09:45

1 Answers1

1

A possible solution is to use a for loop:

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