Getting data

metR implements some functions to easily load data into R either from local files or from remote locations.


The function ReadNetCDF() relies on the ncdf4 package to read netCDF files with ease. It intelligently reads dimensions and data and returns a tidy data.table with optional keyed columns for faster processing afterwards. It can also return an array with named dimensions or a vector, for the case of adding new columns to an existing data.table.

Now that we know the name and the dimensions of the data, we can read it. ReadNetCDF() can also read only a (continuous) subset of the data.

air <- ReadNetCDF(file, subset = list(lat = 90:0, level = 925))

ggplot(air, aes(lon, lat)) +
    geom_contour(aes(z = air, color = ..level..))

Since the most consuming part of reading the file is melting a multidimensional array into a tidy data.table, if we wanted to add another variable to the same data.table we could save time by only returning a vector. It is of the upmost importance that both variables are on the same exact grid.

air[, air2 := ReadNetCDF(file, out = "vector",
                         subset = list(lat = 90:0, level = 300))]

ggplot(air, aes(lon, lat)) +
    geom_contour(aes(z = air2, color = ..level..))

Because ReadNetCDF() can read multiple variables at the same time, the out = "vector" output will be actually return a list of vectors (which integrates seamlessly with the data.table syntax). If one of the variables has degenerate dimensions (dimensions of length 1) then it will be recycled. That means that if the same file has Sea Surface Temperatures (a 2D field) and Air Temperature (a 3D field), then the returned data.table fill have an observation of Air Temperature and Sea Surface Temperature for each vertical level.

The netCDF format is very flexible and this function has not been tested on every possible file so things may break in strange cases. If you have a file that cannot be read with this function, please submit an issue.


Related to this problem, MaskLand() returns a logical vector with TRUE if a point is over land.

air[, land := MaskLand(lon, lat)]

ggplot(air, aes(lon, lat)) +
    geom_tile(aes(fill = land)) +

With this, we can compare mean temperature over land and over sea by latitude.

ggplot(air[, .(air = mean(air) - 273.15), by = .(lat, land)],
       aes(lat, air)) +
    geom_line(aes(color = land))

The resolution of MaskLand() is, in principle, only limited by the polygons used as mask. Currently it can only use maps from the maps package (see ?maps::map).


Finally, GetSMNData() retrieves data from Argentina’s National Weather Service’s public access. This is a rapidly evolving project, and data availability is not guaranteed. Currently available data are hourly station data, daily station maximum and minimum temperature, and global and diffuse radiation measured at Buenos Aires and Ushuaia.

Manipulate data


Empirical Orthogonal Functions (also known as Principal Component Analysis) is a widely use technique for dimensional reduction of large datasets. In R there are multiple packages that implement this methodology (in fact, base R has two functions) but, IMHO, they have awkward interfaces that don’t interact well with data.table (or dplyr) syntax. metR’s EOF() essentially performs a Singular Value Decomposition of the data and returns the left and right singular vectors, and singular values in a tidy format.

In the returned list of data.tables the left (right) singular vectors are fields defined with the dimensions on the left (right) hand of the formula. In this case, the right data.table holds spatial fields and the left data.table holds a timeseries. If the order of the right hand side and left hand side of the formula are reversed, and rotate == FALSE, then the result is the same. Rotation of the singular vectors is perform via stats::varimax() and perform from the (scaled) right singular vector.

For completion, let’s plot each Principal Component.

ggplot(eof$right, aes(lon, lat)) +
    geom_contour_fill(aes(z = gh.t.w), binwidth = 0.01) +
    scale_fill_divergent() +
    coord_polar() +

ggplot(eof$left, aes(date, gh.t.w)) +
        geom_line(aes(color = PC)) +
        scale_x_date(expand = c(0, 0))

Where the 1st Principal Component is clearly the Antarctic Oscillation and the 2nd Principal Component looks like the Pacific–South American Pattern.


As shown above, EOF() needs a complete data matrix. Imputing missing values is a huge problem on it’s own with a lot of different algorithms. metR offers ImputeEOF(), which is an implementation of the DINEOF algorithm for imputation of missing data. It’s interface is similar to that of EOF() but it returns a vector of imputed values.

The imputed vector is returned along with the Root Mean Square Error estimated from crossvalidation and the number of EOFs used in the imputation as attributes. In this case, with 5 EOFs the imputed values have an estimated rmse of 26.9.


Interpolate() is a convenient wrapper of fields::interp.surface() that makes it work better inside data.tables. It can be used to a new grid or to add interpolated values to an existing grid. It’s easy to interpolate multiple values with the formula interface.

# new grid
x.out <- seq(0, 360, by = 10)
y.out <- seq(-90, 0, by = 10)

interpolated <- geopotential[, Interpolate(gh | gh.t.w ~ lon + lat, x.out, y.out), 
                             by = date]

To add interpolated values to an existing data.table use grid = FALSE.



Derivation is the bread and butter of the researcher so Derivate() offers a convenient interface for derivation using finite differences of multidimensional data. It has support for cyclical boundary conditions and for the special case of spherical coordinates (think: Earth).

geopotential[date == date[1],    # think: gh as a function of lon and lat
    c("gh.dlon", "gh.dlat") := Derivate(gh ~ lon + lat, 
                                        cyclical = c(TRUE, FALSE), 
                                        sphere = TRUE)]

ggplot(geopotential[date == date[1]], aes(lon, lat)) +
    geom_contour_fill(aes(z = gh)) +
    geom_vector(aes(dx = gh.dlon, dy = gh.dlat), skip = 2, 
                scale = 3e4) +
#> Warning: Ignoring unknown parameters: scale

There are several wrapers around Derivate() to perform other common related operations, Laplacian(), Divergence() and Vorticity().


Finally, the function GeostrophicWind() computes geostrophic wind from geopotential height.


metR offers several functions related to thermodynamical processes in the atmosphere (see ?thermodynamics). These are IdealGas(), Adiabat(), VirtualTemperature(), MixingRatio(), ClausiusClapeyron() and DewPoint(). Each function represents a different physical relationship between variables and computes one of them from the others.

For example, IdealGas() uses the ideal gas law to compute pressure, temperature or density.

Different variables can be derived by combining these functions. For example, it’s easy to calculate relative humidity from data on temperature and dewpoint, then saturation mixing ratio from pressure and temperature and finally the actual mixing ratio.

Of course, w can be also be computed by DewPoint(p, td = td) which gives essentially the same result: 0.0014548.