Search code examples
rattributesrasterterra

How to access attributes [e.g. time] of terra raster in R?


I have a raster that is read and cropped from a netcdf4 file. The raster looks like this:

> library(terra)

> ncr1
class       : SpatRaster 
dimensions  : 341, 745, 3  (nrow, ncol, nlyr)
resolution  : 1000, 1000  (x, y)
extent      : 1369250, 2114250, -674500, -333500  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=lcc +lat_0=42.5 +lon_0=-100 +lat_1=25 +lat_2=60 +x_0=0 +y_0=0 +ellps=WGS84 +units=m +no_defs 
source      : memory 
names       :    vp_1,    vp_2,    vp_3 
min values  :  174.03,  195.29,  393.66 
max values  :  516.43,  606.79, 1047.61 
time        : 2009-01-01 12:00:00 to 2009-01-03 12:00:00 

> dput(ncr1@ptr$time)
c(1230811200, 1230897600, 1230984000)

As part of the processing I want to do, I want to use the time attribute (I'm not sure if that's the right adjective for that component) as a vector input with my process, such as how doy is used in meteor::hourlyFromDailyRelH() : hourlyFromDailyRelh(relh, tmin, tmax, doy, latitude). I don't know how to call the attribute programatically. It looks like I can use ncr@ptr$time, but it seems like that's the wrong way to do it, based on this question at least. For example:

> library(lubridate)
> pdays <- yday(as_datetime(ncr1@ptr$time))
> pdays
[1] 1 2 3

is wrong? I mean it seems to work, but if there is a more appropriate function in R (or terra) for getting the @ptr$time part, I don't know what it is. I tried terra::cats() and using getSlots(), but those are wrong.


Solution

  • I guess you are looking for the following:

    terra::time(ncr1)