1

I have a NETCDF file with attributes being lon,lat,time,precipitation. The data covers a certain spatial domain. It is daily data from 1960 to 2100.

1) I will like to subset the data spatially (e.g lat[45,50] and lon[-78,-85])from the main domain

2) From the subset, I will like to average over all grids and produce a single column daily time series then write it to a .csv file.

NB: my data contains missing values

ClimateUnboxed
  • 7,106
  • 3
  • 41
  • 86
code123
  • 2,082
  • 4
  • 30
  • 53

3 Answers3

3

Something along these lines ought to work

library(raster)
b <- brick('file.nc')
be <- crop(b, extent(-85, -78, 45, 50))
a <- aggregate(be, dim(be)[2:1], na.rm=TRUE)
v <- values(a)
write.csv(v, 'precip.csv', row.names=FALSE)

Normally, to get the date as well:

date <- getZ(be)

Or

date <- names(a)
date <- gsub('X', '', date)

And then

v <- data.frame(date=date, prec=v)
write.csv(v, 'precip.csv', row.names=FALSE)

Whether or not this date is human readable depends on how it is stored in the ncdf file (i.e. whether certain conventions are followed or not).

Robert Hijmans
  • 40,301
  • 4
  • 55
  • 63
3

This would do the cut and the averaging but writes the answer to another netcdf. If you really need CSV, then you would need to use that part of the solution above.

cdo fldmean -sellonlatbox,-85,-78,45,50 in.nc out.nc
ClimateUnboxed
  • 7,106
  • 3
  • 41
  • 86
1
library (ncdf4)

nc <- nc_open("netcdf.nc")

lon <- ncvar_get(nc,"lon")
lat <- ncvar_get(nc,"lat")
time <- ncvar_get(nc,"time")

lon_lim <- c(45,50)
lat_lim <- c(-78,-85)

lon_ind <- which(lon >= lon_lim[1] & lon <= lon_lim[2])
lat_ind <- which(lat >= lat_lim[1] & lat <= lat_lim[2])

precip <- ncvar_get(nc,"precip",start = c(lon_ind[1],lat_ind[1],time),count = c(length(lon_ind),length(lat_ind),length(time)))

ts <- apply(precip,3,mean,na.rm=TRUE)

  • please share some explanation about how this code solve the problem – OMR Dec 03 '20 at 18:34
  • warning: this solution will give the INCORRECT answer as it does not weight for the cells getting smaller at higher latitudes... See this answer for example: https://stackoverflow.com/questions/60571445/get-mean-of-netcdf-file-using-xarray/65353505#65353505 – ClimateUnboxed Dec 18 '20 at 08:59