[R] Indexing zoo objects

Gabor Grothendieck ggrothendieck at gmail.com
Wed Mar 3 11:41:22 CET 2010


I would normally use 'which', as already suggested, but if, as in your
example, the 26th were the last in the series and this is known then
these would all work too to get the time of the 3rd last (2nd prior to
the last):

time(z)[length(z) - 2]

time(tail(z, 3)[1, ])
head(tail(time(z), 3), 1)

time(head(tail(z, 3), 1))
tail(time(z), 3)[1]

If we do not know that the 26th is last then applying any of the above
to w would work:

w <- window(z, end = as.Date("2003-11-26"))

or in combination with xts which has a special notation in place of
the window function:

library(xts)
time(z)[length(as.xts(z)["::2003-11-23"]) - 2]

and this would work too:

time(z)[length(time(z) <= as.Date("2003-11-23")) - 2]


On Wed, Mar 3, 2010 at 4:00 AM, Achim Zeileis <Achim.Zeileis at uibk.ac.at> wrote:
> On Wed, 3 Mar 2010, Worik R wrote:
>
>> I have a zoo object z
>>
>> z
>>          Value
>> 2003-11-15  2.22
>> 2003-11-17  2.26
>> 2003-11-19  2.28
>> 2003-11-22  2.54
>> 2003-11-26  2.55
>>
>> I wish to find the entry 2 entries before "2003-11-26".  How do I do this?
>
> If you want to find out that this is at the third position you can ask
>
>  which(time(z) == "2003-11-26") - 2
>
> and the whole observation could be extracted via
>
>  z[which(time(z) == "2003-11-26") - 2, ]
>
> If you want to query just the data value you could also use lag(), e.g.
>
>  window(lag(z, -2), as.Date("2003-11-26"))
>
> hth,
> Z
>
>> I thought I might be able to say index(z["2003-11-26"]) and have it return
>> 5
>> so I could then say z[3].  But this does not work.
>>
>> I can not find an answer in ?index
>>
>> In the meantime I am using a loop, can any one help?
>>
>> cheers
>> Worik
>>
>>        [[alternative HTML version deleted]]
>>
>> ______________________________________________
>> R-help at r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide
>> http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
>>
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list