Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Monthly average from netCDF files in R

Tags:

r

netcdf4

I have one netCDF file (.nc) with 16 years(1998 - 2014) worth of daily precipitation (5844 layers). The 3 dimensions are time (size 5844), latitude (size 19) and longitude (size 20) Is there a straightforward approach in R to compute for each rastercell:

  • Monthly & yearly average
  • A cummulative comparison (e.g. jan-mar compared to the average of all jan-mar)

So far I have:

library(ncdf4)
library(raster)

Rname <- 'F:/extracted_rain.nc'
rainfall <- nc_open(Rname)
readRainfall <- ncvar_get(rainfall, "rain") #"rain" is float name
raster_rainfall <- raster(Rname, varname = "rain") # also tried brick()
asdatadates <- as.Date(rainfall$dim$time$vals/24, origin='1998-01-01') #The time interval is per 24 hours

My first challenge will be the compuatation of monthly averages for each raster cell. I'm not sure how best to proceed while keeping the ultimate goal (cummulative comparison) in mind. How can I easily access only days from a certain month?

raster(readRainfall[,,500])) # doesn't seem like a straightforward approach

Hopefully I made my question clear, a first push in the right direction would be much appreciated. Sample data here

like image 202
Jobbo90 Avatar asked Feb 06 '23 11:02

Jobbo90


1 Answers

The question asked for a solution in R, but in case anyone is looking to do this task and wants a simple alternative command-line solution, these kind of statistics are the bread and butter of CDO

Monthly averages:

cdo monmean in.nc monmean.nc

Annual averages:

cdo yearmean in.nc yearmean.nc

Make the average of all the Jan, Feb etc:

cdo ymonmean in.nc ymonmean.nc

The monthly anomaly relative to the long term annual cycle:

cdo sub monmean.nc ymonmean.nc monanom.nc

Then you want a specific month, just select with selmon, or seldate.

you can call these functions from R using the system command.

like image 182
Adrian Tompkins Avatar answered Feb 19 '23 22:02

Adrian Tompkins