summary: how to convert a 3D array (as obtained from ncdf4::ncvar_get)
to a dataframe suitable for use by lattice::levelplot(), e.g.,
levelplot(conc ~ lon * lat | lev, data = data.frame)
details:
I have atmospheric data in netCDF files specifying gas concentrations
over a 3D space with dimensions longitude, latitude, and (vertical)
level. I need to plot the data by level. Since there are several levels,
I'm guessing I should use package=lattice, which I have not previously
used. (I have used package=fields, and I would like to plot the levels
over a map, but lattice seems to provide the best way to organize
multiple plots--please correct me if wrong.)
From reading Sarkar's excellent lattice book
http://dx.doi.org/10.1007/978-0-387-75969-2
it seems that one best provides data to lattice::levelplot() via
dataframe, since the dataframe provides a sort of namespace for the
trellis "formula." I know that ncdf4::ncvar_get will return my
concentrations as the values in a 3D array with dimensions={lon, lat,
lev} so I'm trying to find a way to convert a 3D array to a dataframe.
Here's my small, self-contained example:
lon=11
lat=7
lev=5
len=lon*lat*lev
array.3d <- array(data=c(1:len), dim=c(lat, lon, lev))
# Rewrite the array values "more spatially," i.e., row-wise from
# bottom left. If there's a more-R-ish way to fill this array
# as specified, please let me know: I know 'for' loops are deprecated
# in R.
i=1
for (z in 1:lev) {
for (x in lat:1) {
for (y in 1:lon) {
array.3d[x,y,z]=i ; i=i+1
}
}
}
produces (with rows=latitudes and cols=longitudes)