2

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.

John Polo
  • 547
  • 1
  • 8
  • 25
  • @akrun I made an edit. – John Polo Feb 07 '22 at 16:11
  • 1
    You could have done `?terra` and then find (Ctrl-F) "time". It is generally not a good idea to directly access the `@ptr$` data/methods. – Robert Hijmans Feb 07 '22 at 17:14
  • @RobertHijmans thank you. I was thinking about the raster as an S4 object and trying to figure out how to access the parts of the object that are not the specific data, which I identify with the cell values. The `time` slot or attribute or whatever it's called is ancillary, but still useful at times. Knowing the right way to get the ancillary stuff is still not clear to me with S4 objects, except through `@(name1)$(name2)`, and I didn't know that there was a specific `time` function for this object. – John Polo Feb 07 '22 at 18:12
  • In a well designed package you should not need to access slots directly (and doing so frequently leads to problems). – Robert Hijmans Feb 07 '22 at 18:45

1 Answers1

2

I guess you are looking for the following:

terra::time(ncr1)
lovalery
  • 4,524
  • 3
  • 14
  • 28