Mike Furlender
Mike Furlender

Reputation: 4019

R: Subset a zoo object?

Given a date I can access the appropriate element in a zoo vector. For example:

z[as.POSIXct(1213708500, origin="1970-01-01")]

this returns

2008-06-17 14:15:00 
           -8.28123 

I would like to get a vector of 30 consecutive elements (ending with the element above).

How do I do that (efficiently) without knowing the time stamp of the starting element?

I know that I can do this with the window function, but it requires a start time and an end time.

Upvotes: 4

Views: 6050

Answers (1)

Dirk is no longer here
Dirk is no longer here

Reputation: 368191

Use something like

ind <- which(index(z)==as.POSIXct(1213708500, origin="1970-01-01")) + seq(-29,0)

followed by

z[ind]

where the which() gives you the index of the match, from which you can then pick the thirty consecutive elements by normal indexing.

Upvotes: 5

Related Questions