Question

If I have a list of zoo objects, how do I go about referring to particular values by list index([[]]) and date? For example:

require("zoo")
require("tseries")
require("lubridate")

z = zoo(c(1,2,3), as.Date(c("2000/1/1", "2000/2/1", "2000/3/1")))
z1 = zoo(c(1,2,3), as.Date(c("2000/1/1", "2000/2/1", "2000/3/1")))
z2 = zoo(c(10,20,30), as.Date(c("2000/1/1", "2000/2/1", "2000/3/1")))
z3 = zoo(c(100,200,300), as.Date(c("2000/1/1", "2000/2/1", "2000/3/1")))
> l = list(z1,z2,z3)
> l
[[1]]
2000-01-01 2000-02-01 2000-03-01 
         1          2          3 

[[2]]
2000-01-01 2000-02-01 2000-03-01 
        10         20         30 

[[3]]
2000-01-01 2000-02-01 2000-03-01 
       100        200        300 

My goal is to return a value for each row that has the column number of the month from the index. Desired output on above data would be:

1, 20, 300 (can be a zoo object, vector, whatever is easiest to show). I'll coerce it how I need.

The way I've been trying to code it is (among others):

monthNumbs = month(index(l[[1]]))
l[[monthNumbs]][index(l)]

I know this is structurally incorrect; but it's how I'm viewing the data structures. Any help would be great...

Was it helpful?

Solution

If I well understood your question , I think you can do this for example:

## loop through the index of the list
## for each zoo object l[[x]]  you get months index
## and you compare it to current index
unlist(lapply(seq_along(l),
        function(x)l[[x]][month(index(l[[x]]))==x]))
[1]   1  20 300

EDIT Another alternative using xts package:

If all your zoo objects have teh same index, you can merge them to get a matrix structure:

library(xts)
mm <- do.call(merge,lapply(l,as.xts))
           c.1..2..3. c.10..20..30. c.100..200..300.
2000-01-01          1            10              100
2000-02-01          2            20              200
2000-03-01          3            30              300

Then you get the diagonales values like this :

as.matrix(mm)[col(mm)==row(mm)]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top