The rbeni package contains a set of functions that let you do standard tasks working with NetCDF files on one line and let you quickly convert the contents of a NetCDF file into a tidy data frame (tibble).
Here is a demonstration example.
Load the package and read the contents of one NetCDF file.
library(rbeni)
library(tidyverse) # depends
nc <- read_nc_onefile("~/data/stocker20gmd_outputs/global/global_FULL_fAPAR3g_v2_2000_2016.a.gpp.nc")
## Warning: All formats failed to parse. No formats found.
The returned object nc
is a list with:
print(ls(nc))
## [1] "lat" "lon" "time" "varnams" "vars"
lon
: vector of longitudes of gridcell mid-pointslat
: vector of latitudes of gridcell mid-pointstime
: vector of dates created by lubridate::ymd dates
varnams
: vector of all variable names as strings,vars
: named list of the data arrays (lon x lat [x time]) for each variable. The names of that list correspond to varnams
.## available variable names
print(nc$varnams)
## [1] "gpp"
## available variable arrays (names thereof)
print(ls(nc$vars))
## [1] "gpp"
## dimension of variable array number one
print(dim(nc$vars[[1]]))
## [1] 720 360 17
The object nc
can be converted into a tidy dataframe.
df <- nc_to_df(nc, varnam = "gpp")
head(df)
The data frame is organised by gridcells along rows. Since the NetCDF contains multiple time steps, the time series are nested inside the column data
for each gridcell.
head(df$data[[1]])
Note that df
contains rows for all gridcells, also those that have no data (here, non-land gridcells). That’s why the above time series data frame is empty.
Since object nc
contains data for multiple time steps, we can select a single time step and get an object that has only lon and lat.
nc_2d <- slice_nc(nc, 1)
This 2D data frame can be converted back into a grid:
gridded <- df_to_grid(nc_2d, varnam = "data")
gridd
(This makes sense only if df
is not a nested data frame and contains only data for one time step.)
This can now be used to create a nice map.
gg <- plot_map3(nc_2d, varnam = "gpp", plot_title = "GPP", latmin = -65, latmax = 85)
## Warning: Overwriting nbin after defining breaks with scales::pretty_breaks().
## Warning in plot_discrete_cbar(breaks = breaks_with, colors = colorscale, :
## Ignoring RColorBrewer palette 'Greys', since colors were passed manually
## Warning: Removed 43200 rows containing missing values (geom_tile).
## Warning: Removed 637 row(s) containing missing values (geom_path).
gg
Very useful also to quickly write the nc
object into a new NetCDF file.
write_nc2(nc, path = "./test.nc")
## Warning: Using all variables in nc object.
## Writing to file: ./test.nc...
## [1] "./test.nc"