Search code examples
rnetcdfr-stars

Subsetting ncdf file using stars package in R


I am trying to subset a climatic variable from Copernicus.

devtools::install_github("r-spatial/stars")
library(stars)

library(ncdf4)
library(RNetCDF)

pp <- read_ncdf("~/climate_data/pp_ens_mean_0.1deg_reg_v25.0e.nc", proxy = TRUE)

> print(pp)
netcdf source stars proxy object from:
[1] "[...]/pp_ens_mean_0.1deg_reg_v25.0e.nc"

Available nc variables:
pp

dimension(s):
          from    to         offset  delta  refsys point values x/y
longitude    1   705       -25.0001    0.1  WGS 84    NA   NULL [x]
latitude     1   465        24.9999    0.1  WGS 84    NA   NULL [y]
time         1 26298 1950-01-01 UTC 1 days POSIXct    NA   NULL      

This is what I get as a proxy.

I would like to subset between 10°E and 25°E in longitude, and 55°N and 70°N in latitude. I tried this but it is not working and I do not really figure out why.

pp <- read_ncdf(pp, 
                var = pp, 
                ncsub = cbind(start = c(10, 55, 1), 
                               count = c(25, 70, 26298)))

Any ideas? Many thanks for the precious help.


Solution

  • Answer thanks to @Chris:

    devtools::install_github("r-spatial/stars")
    library(stars)
    
    library(ncdf4)
    library(RNetCDF)
    
    pp <- read_ncdf("C:/Users/Dell/Desktop/~/climate_data/pp_ens_mean_0.1deg_reg_v25.0e.nc", proxy = TRUE)
    
    print(pp)
    
    bb = st_bbox(c(xmin=10.00, ymin=55.00, 
                   xmax=25.00, ymax=70.00),
                   crs = st_crs(4326))
    
    pp_sub = pp[bb]
    
    > print(pp_sub)
    netcdf source stars proxy object from:
    [1] "[...]/pp_ens_mean_0.1deg_reg_v25.0e.nc"
    
    Available nc variables:
    pp
    
    dimension(s):
              from    to         offset  delta  refsys point values x/y
    longitude  351   501       -25.0001    0.1  WGS 84    NA   NULL [x]
    latitude   301   451        24.9999    0.1  WGS 84    NA   NULL [y]
    time         1 26298 1950-01-01 UTC 1 days POSIXct    NA   NULL