Search code examples
rnetcdfr-rasternetcdf4

Convert multidimensional NetCDF to Tif in R


I have .nc file sizing around 651 MB with a couple of datasets (daily) (rr_mrg_19810101_20181231_ENACT.nc) data. I need to convert (rr_mrg_19810101_20181231_ENACT.nc) dataset to multiple GeoTIFF (one .tif for each time slice, monthly). Similarly, i want to read the time series. But I found

Error in .local(x, time, ...) : 
time must has the same length as the number of layers in RasterBrick][1]

Here is what i did

library(raster)
library(zoo)
library(rts)
       
TRF = brick("rr_mrg_19810101_20181231_ENACT.nc")
crs(TRF) <- "+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 
+towgs84=0,0,0"
Awash_Extent<-c(37,44, 7,12)
Awash_E_resize<- crop(TRF,Awash_Extent)

Awash_Month<-seq(as.Date('1981-01-01'),as.Date('2018-12-31'),by = 
"month")

rt <- rts(Awash_E_resize, Awash_Month) 

write.rts(Awash_E_resize, filename='Awash_TRF_1981_2018_mon.tif', 
overwrite=TRUE)

Can you help me on the issue?


Solution

  • Something as simple as this can do that

    library(raster)
    b <- brick("rr_mrg_19810101_20181231_ENACT.nc")
    writeRaster(b, "timeslice.tif", bylayer=TRUE)
    

    Based on your expanded question:

    Read the values with terra (no need for other packages)

    library(terra)    
    TRF = rast("rr_mrg_19810101_20181231_ENACT.nc")
    Awash_Extent<-c(37,44, 7,12)
    Awash_E_resize<- crop(TRF,Awash_Extent)
    

    I create something similar here:

    A <- rast(ext(37,44, 7,12), nlyr=365)
    values(A) <- runif(size(A))
    terra::time(A) <- seq(as.Date('1981-01-01'), as.Date('1981-12-31'), 1)
    

    Now aggregate by month:

    m <- months(time(A))
    f <- factor(m, levels=unique(m))
    
    B <- tapp(A, m, fun=sum)
    B
    #class       : SpatRaster 
    #dimensions  : 10, 10, 12  (nrow, ncol, nlyr)
    #resolution  : 0.7, 0.5  (x, y)
    #extent      : 37, 44, 7, 12  (xmin, xmax, ymin, ymax)
    #coord. ref. : lon/lat WGS 84 
    #source      : memory 
    #names       :  January, February,    March,    April,      May,     June, ... 
    #min values  : 12.49764, 10.47718, 11.80974, 11.29624, 11.01105, 10.83298, ... 
    #max values  : 18.90536, 16.95743, 20.57114, 18.12099, 18.46543, 18.98500, ... 
     
    

    You could add a filename= argument to tapp, but if you want to save the layers as separate files you can use writeRaster instead. But with terra you need to provide the filenames yourself.

     fnames <- paste0("rain_", 1:nlyr(B), ".tif")
     writeRaster(B, fnames, overwrite=T)
    

    (there is a warning about file_ext that you can ignore)