Using this as a source : How to concatenate monthly TRMM netCDF files into a single netCDF file using NCO or R on windows 7?
install.packages("ncdf4")
library(ncdf4)
install.packages("abind")
library(abind)
install.packages("RNetCDF")
library(RNetCDF)
install.packages("ncdf.tools")
library(ncdf.tools)
filenames=read.csv('TRMM.filenames.csv',head=F)
filenames=as.character(filenames[,1])
n.lon=4
n.lat=7
NA.matrix=matrix(rep(NA,n.lon*n.lat),nrow=n.lon)
prcp=array(NA.matrix,c(n.lon,n.lat,1))
for (i in 1:length(filenames)){ncdata=nc_open(filenames[i])
+ nc=ncvar_get(ncdata,"precipitation") prcp=abind(prcp,nc)}
prcp=prcp[,,-1]
dim(prcp)
saveRDS(prcp,'TRMM.all.rds')
I was able to create an rds file. However, I'm really interested in saving it as an nc file. I tried creating a new netCDF file with a 12 steps (one for each month) time dimension by :
dimx <- ncdim_def( "Lon", "degreesE", as.double(-90:-87))
dimy <- ncdim_def( "Lat", "degreesN", as.double(14:16))
dimTime <- ncdim_def( "Time", "months", 1:12, unlim=TRUE )
dimlist<-list(dimx,dimy,dimTime)
precip.ncvar<- ncvar_def("Precip", "mm/hr", dimlist, -1, longname="Precipitation", prec="float")
precip.nccreate<- nc_create( "precip.nccreate.nc", precip.ncvar, force_v4=FALSE, verbose=FALSE )
nc_close(precip.nccreate)
Now the challenge is to add the precipitation data to each month.
Following the first script I tried using the ncvar_put
function without success.
filenames1=read.csv('TRMM.filenames.csv',head=F)
filenames1=as.character(filenames1[,1])
for (i in 1:length(filenames1)){ncdata1=nc_open(filenames1[i])
nc1=ncvar_get(ncdata1,"precipitation")
prcp1=abind(prcp1,nc1)}
n.lon1=4
n.lat1=7
data2d<-(4*7)
for (i in 1:length(filenames1))
ncvar_put( precip.nccreate, precip.ncvar, data2d, start=c(1), count=c(1) )
precip.nccreate<- nc_create( "precip.nccreate.nc", precip.ncvar, force_v4=FALSE, verbose=FALSE )
To which I got
Error in ncvar_put(precip.nccreate, precip.ncvar, data2d, start = c(1), : object 'precip.nccreate' not found
Error in nc_create("precip.nccreate.nc", precip.ncvar, force_v4 = FALSE, : object 'precip.ncvar' not found
Anyway, I guess I'm just trying to find an easy way to concatenate multiple netcdf files into a single netcdf.
Thanks