Access zoo or xts index

18,109

Solution 1

From the help for ?zoo, there are two convenience methods to access the data in zoo objects:

  • coredata() returns the data in the zoo object
  • index() returns the index

For example:

x.Date <- as.Date("2003-02-01") + c(1, 3, 7, 9, 14) - 1
x <- zoo(rnorm(5), x.Date)

index(x)
[1] "2003-02-01" "2003-02-03" "2003-02-07" "2003-02-09" "2003-02-14"

coredata(x)
[1] -1.2487943  0.8911630  1.2713133 -0.1024638  0.2989194

Solution 2

In general when you see attr, this means that this data is an attribute of an object.

attributes function can be used to dump all attributes as a list, so you can access certain element with $:

attributes(ObjZoo)$index

attr gives you direct access to the attribute by its name:

attr(ObjZoo,"index")

In fact this is what index does:

> zoo:::index.zoo

function (x, ...) 
{
    attr(x, "index")
}
<environment: namespace:zoo>
Share:
18,109

Related videos on Youtube

feschet
Author by

feschet

Updated on June 04, 2022

Comments

  • feschet
    feschet almost 2 years

    I am using zoo objects, buy my question also applies to xts objects. It looks to me like it is a one column vector with an index. In my case the index is the vector of dates and the one column vector my data. All is good except that I would like to access the dates (from the index).

    For example I have the following result:

    ObjZoo <- structure(c(10, 20), .Dim = c(2L, 1L), index = c(14788, 14789),
                        class = "zoo", .Dimnames = list(NULL, "Data"))
    unclass(ObjZoo)
    #      Data
    # [1,]   10
    # [2,]   20
    # attr(,"index")
    # [1] 14788 14789
    

    I want to get 14789 in a variable or a vector, but I'm not sure how to access it.

    • Matt Bannert
      Matt Bannert almost 13 years
      Welcome! Here's a related thread emphasizing the additional relevance of mbq's answer even if Andrie's fits perfectly.
    • Dirk Eddelbuettel
      Dirk Eddelbuettel almost 13 years
      I spend hours looking for that Really? Maybe you should have started with the excellent zoo vignettes.
    • Andrie
      Andrie almost 13 years
      @DirkEddelbuettel, to be fair to the OP, thinking back to my early days with R, I also struggled to make sense of the help files. ts objects were a complete mystery (they still are, to some extent). Yes it's true that I found the answer to this question within 2 minutes of reading ?zoo, but still, I have sympathy with the struggles of the newby.