Sie sind auf Seite 1von 2

1/3/2019 RPubs - How to open and work with NetCDF data in R

RPubs brought to you by RStudio


How to open and work with NetCDF data in R by Alison Boyer Last updated over 1 year ago
Sign in Register

There are 10 global attributes which provide metadata information about the file.
Commentscode
We need to capture these data in the lat, lon, and time dimensions. The following (–) reads Share Hide Toolbars
the latitudes,
longitudes, and time of each NDVI observation and saves them in memory.

lon <- ncvar_get(nc_data, "lon")


lat <- ncvar_get(nc_data, "lat", verbose = F)
t <- ncvar_get(nc_data, "time")

head(lon) # look at the first few entries in the longitude vector

## [1] -179.9583 -179.8750 -179.7917 -179.7083 -179.6250 -179.5417

Read in the data from the NDVI variable and verify the dimensions of the array. There should be 4320 lons, 840
lats, and 31 times

ndvi.array <- ncvar_get(nc_data, "NDVI") # store the data in a 3-dimensional array


dim(ndvi.array)

## [1] 4320 840 31

Other pertinent information about the NDVI variable: Lets’s see what fill value was used for missing data.

fillvalue <- ncatt_get(nc_data, "NDVI", "_FillValue")


fillvalue

## $hasatt
## [1] TRUE
##
## $value
## [1] -9999

The fill value is -9999.

All done reading in the data. We can close the netCDF file.

nc_close(nc_data)

Working with the data


So, now we have the entire array of NDVI values for 4320 x 840 grid cells over each of 31 years in R. What can
we do with it?

First, a little housekeeping. Let’s replace all those pesky fill values with the R-standard ‘NA’.

ndvi.array[ndvi.array == fillvalue$value] <- NA

Let’s get one year of the NDVI data and plot it.

Time is the third dimension of the “ndvi.array”. The first time slice represents the growing season of 1982.

https://rpubs.com/boyerag/297592?fbclid=IwAR3-gYtP9VawTI8pk9QRXiCWiR07hGKbGe2975q-EEBG-GUP3mm44QMz9WA 1/2
1/3/2019 RPubs - How to open and work with NetCDF data in R

https://rpubs.com/boyerag/297592?fbclid=IwAR3-gYtP9VawTI8pk9QRXiCWiR07hGKbGe2975q-EEBG-GUP3mm44QMz9WA 2/2