Question

Let say I have this zoo vector

mine <- zoo(c(rep(0,4),rep(1,4),rep(0,5),rep(1,23),rep(0,4),rep(1,2)),as.chron(seq(1:42)))

And I want to extract several elements in some order

> mine[14]
01/15/70 
       1 
> mine[5]
01/06/70 
       1 
> mine[41]
02/11/70 
       1 

It works!. But now I try to do it in a different way

zz <- c(14, 5, 41)
mine[zz]

01/06/70 01/15/70 02/11/70 
       1        1        1 

I don't know why I get it in a different order. How can I keep the order I want, the order of my list ?? I don't mind if it's a list, a vector, by columns or by row, but I'd like to get it in the order I've asked for.

cheers

Was it helpful?

Solution

The answer to why zoo does this is that it has a method for the function [ ([.zoo), and it creates a new zoo object from the subsetted values, which it logically wants to reorder so that it is a valid zoo object.

You can achieve what you want by accessing the time indices and data via the relevant accessor functions:

> index(mine)[c(14, 5, 41)]
[1] 01/15/70 01/06/70 02/11/70
> coredata(mine)[c(14, 5, 41)]
[1] 1 1 1

If you want to combine this into a single step, write your own fun to do:

myExtract <- function(x, want) {
    out <- coredata(mine)[want]
    names(out) <- index(x)[want]
    out
}

Which gives:

> myExtract(mine, want = c(14, 5, 41))
01/15/70 01/06/70 02/11/70 
       1        1        1
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top