rnetcdfr-rasterterra

Faster efficient way to crop netcdf in R


I have a .nc/netcdf file which is about 1GB in size. Trying to crop and make it smaller with the following code:

  r <- terra::rast("myfile.nc")
  r2 <- terra::crop(x = r, y=terra::ext(-79, -72, 0, 12.4))

fails in a 16GB RAM machine. By failing I mean it does not return any results in 15 minutes and freezes my RStudio session if I try to stop the running code. Thus I have no error message to post here.

What alternative to terra::crop() should I consider to use on netcdf files?


Solution

  • Dealing with (NetCDF) files with many layers (time steps) can be very slow when using (a standard approach with) GDAL, which is what terra uses.

    There now is a faster approach, using the "multi-dimensional" interface like this

    library(terra)
    r <- rast("myfile.nc", md=TRUE)
    r2 <- crop(r, ext(-79, -72, 0, 12.4))
    

    Alternatively, you could the otherwise obsolete raster package for this:

    library(raster)
    r <- brick("myfile.nc")
    r2 <- crop(r, extent(-79, -72, 0, 12.4))