I have a raster stack and I want to add to it a Date field which will include the year-month-day for every rasterlayer. I have my dates in a one column data.frame. I tried to do this with addLayer but it didn't work.

Any ideas?



ras = raster(matrix(1:30,3,4))
my_s = stack(ras,ras,ras,ras,ras)
my_s <- addLayer(my_s, dt)

Adding a layer doesn't make sense because you are trying to associate a value with each layer, rather than creating a new NxM layer of values. Use setZ instead:


ras = raster(matrix(1:30,3,4))
my_s = stack(ras,ras,ras,ras,ras)
my_s <- setZ(my_s, dt[,1], "SampleDate")

get the values back with getZ - they are still dates:

> getZ(my_s)
[1] "2010-11-01" "2008-03-25" "2007-03-14" "2007-03-18" "2007-03-20"
> class(getZ(my_s))
[1] "Date"
  • Thanks @Spacedman. That is what I was looking for.
    – geo_dd
    Jan 25 '19 at 8:48
  • One question though, in this way, if I change my raster stack in raster bric the z are not prezerved. Is there a way to always preserve it within different calculations?
    – geo_dd
    Jan 25 '19 at 9:20
  • 1
    No, it seems you have to pass them on explicitly: b = brick(s);setZ(b, getZ(s)) or maybe b=brick(s); b@z = s@z to copy the Z component of the object directly. Z's are "in development" according to the help(setZ).
    – Spacedman
    Jan 25 '19 at 10:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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