2
votes

I would like to know how can I stack different raster datasets through time dimension in R.

Concretely:

I have a set of ncdf files that contain rain data per month. I want to merge these datasets through the time dimension so that I have a unique dataset but with time dimension. To do so I stacked these datasets so my nlayers are different periods of time. I would like to pass this nlayers to the time dimension, so if now I have 3 nlayers, I would like to have 3 periods of time.

   nc0298<- stack("3a12.19980201.7.nc", varname="sfcr")  #Rain in 02/1998
   nc0398<- stack("3a12.19980301.7.nc", varname="sfcr")  #Rain in 03/1998
   nc0498<- stack("3a12.19980401.7.nc", varname="sfcr")

  data <- raster::stack(nc0298, nc0398, nc0498)
  print(data)

Output: class : RasterStack dimensions : 22, 27, 594, 3 (nrow, ncol, ncell, nlayers) resolution : 0.5, 0.5 (x, y) extent : 2, 15.5, 3.5, 14.5 (xmin, xmax, ymin, ymax) coord. ref. : +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0 names : surface.rain..mm.hr..1, surface.rain..mm.hr..2, surface.rain..mm.hr..3

But instead of having it in nlayers I would like to have in time dimension: data@layers

Output: 3 dimensions: time Size:1 * is unlimited * units: hours since 1998-4-1 0 longitude Size:27 units: degrees_east long_name: Longitude latitude Size:22 units: degrees_north long_name: Latitude

here we can see that my time dimension is still size 1.

I have both conceptual problems and code ones, so any suggestion explanation will help.

The data files can be obtained at: link

Many thanks,

PD: I am an student of economics so I am an ignorant in spatial analysis and geography. I have intermediate knowledge in R but also in Matlab and Python. If someone have an answer for these programs it could also help me.

this is my first question in a community so sorry for my mistakes.

1
Thanks for the answer and I understand, sorry. I created a repository in github link with the data I use since I don't know how to generate random example data for this case. In the repository it is also explained how to download the data from the original source. Once downloaded to the working directory I think with the previous lines of code should work. I use the libraries RNetCDF, raster but I am not sure if they are necessary now.Albert Rodríguez

1 Answers

0
votes

The link to your data files is dead unfortunately, so I can not test it myself, but one solution using Python could be:

from netCDF4 import MFDataset
import glob

ncfiles = glob.glob('*.nc', recursive=True)
data = MFDataset(ncfiles, aggdim='time')

With the aggdim argument set to your time variable it should create the additional dimension that you are looking for. globis simply useful for reading multiple ncdf files in a folder, make sure to set it to the directory where your files are located.