3

I want to read a specific layer from a multilayer raster (format ncdf) using terra package. I want to extract each layer by polygon using terra package (it is a very fast way to extract values). I know there are other packages to open my multilayer raster but I don't want to use them. I want to use terra package but with multilayers I have many errors.

So, I tried:

 r <- terra::rast(r1,nlyrs=nlyr(4))## I have a error :unable to find an inherited method #for function ‘nlyr’ for signature ‘"numeric"’
 

I tried :

r <- terra::rast(r1, 1) ## no error   

but when I want to extract values from raster. I have this :

uat$ex <- terra::extract(r,vect(uat), fun = mean, na.rm =T)[,2]
 

###
 error: [extract] raster has no value

2
  • Is r1 a character string with a netCDF file name here? Its not clear.
    – Spacedman
    Sep 9, 2021 at 18:53
  • Yes, r1 is a character string with netCDF file name
    – Alex.V
    Sep 10, 2021 at 7:15

2 Answers 2

6

I don't see a way to read in only some layers from a NetCDF using terra::rast - it just doesn't take any extra args except subds when reading a file and that doesn't apply here, it seems.

The solution would be to read the NetCDF and then select the layers you need by name or number.

Read in:

> t1 = terra::rast("./s1.nc")

How many layers?

> dim(t1)
[1] 180 360   3

Names are?

> names(t1)
[1] "variable_z=1" "variable_z=2" "variable_z=3"

Get second layer by name:

> t1[names(t1)[2]]
class       : SpatRaster 
dimensions  : 180, 360, 1  (nrow, ncol, nlyr)
resolution  : 1, 1  (x, y)
extent      : -180, 180, -90, 90  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=longlat +datum=WGS84 +no_defs 
source      : s1.nc 
varname     : variable 
name        : variable_z=2 

Or equivalently t1[[2]] to get by number.

Note that the source here is given as s1.nc which I think means it hasn't read the NetCDF into memory yet, hence this is as efficient as reading a single layer would be in memory terms.

2

It works:

rss <- "/ncdffilename.nc"##  having 60 layers (it's a raster with one single variable for 60 years), the variable name is "cdd"
names(rss) <- "cdd" ## not necessary
r1 <- terra::rast(rss,subds = "cdd") ## select the variable name
r <- r1[[1]] ## give me the first layer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.