[R] Indexing zoo objects

0 views
Skip to first unread message

Worik R

unread,
Mar 2, 2010, 10:54:47 PM3/2/10
to r-help
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?

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-h...@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.

Achim Zeileis

unread,
Mar 3, 2010, 4:00:35 AM3/3/10
to Worik R, r-help
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

Gabor Grothendieck

unread,
Mar 3, 2010, 5:41:22 AM3/3/10
to Worik R, r-help, Achim Zeileis
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]

Reply all
Reply to author
Forward
0 new messages