R: index () cannot return the desired class

I have the following xts object with indexClass "Date". index(data)gives me the "POSIXct" object. I thought I would index(data)return a Date object.

How can I get a date object from index()?

str(data)
An ‘xts’ object from 2007-01-15 to 2012-04-27 containing:
  Data: num [1:1282, 1:5] 1881 2003 2064 2026 2098 ...
 - attr(*, "dimnames")=List of 2
  ..$ : NULL
  ..$ : chr [1:5] "open" "high" "low" "close" ...
  Indexed by objects of class: [Date] TZ: GMT
  xts Attributes:  
List of 2
 $ tclass: chr "Date"
 $ tzone : chr "GMT"

 indexClass(data)
 "Date"

str(index(data))
Class 'POSIXct'  atomic [1:1282] 1.17e+09 1.17e+09 1.17e+09 1.17e+09 1.17e+09 ...
  ..- attr(*, "tzone")= chr "GMT"
  ..- attr(*, "tclass")= chr "Date"
+3
source share
1 answer

Quick answer: Dates do not have time zones. So it (I suppose) should wrap your date in POSIXct in order to save timezone information.

Here is an example without time zones where it shows the behavior you expect:

x=xts(1:10, seq.Date(as.Date('2012-01-01'),by=1,length.out=10))
indexClass(x)
# [1] "Date"
index(x)
# "2012-01-01" "2012-01-02" "2012-01-03" "2012-01-04" "2012-01-05" "2012-01-06" "2012-01-07" "2012-01-08" "2012-01-09" "2012-01-10"
str(index(x))
# Date[1:10], format: "2012-01-01" "2012-01-02" "2012-01-03" "2012-01-04" "2012-01-05" "2012-01-06" "2012-01-07" "2012-01-08" "2012-01-09" "2012-01-10"

UPDATE: adding the tzone attribute to the xts object does not change anything:

x=xts(1:10, seq.Date(as.Date('2012-01-01'),by=1,length.out=10), tzone="GMT")
str(index(x))
# Date[1:10], format: "2012-01-01" "2012-01-02" "2012-01-03" "2012-01-04" "2012-01-05" "2012-01-06" "2012-01-07" "2012-01-08" "2012-01-09" "2012-01-10"

This is despite the fact that str (x) gives the same result as you:

An ‘xts’ object from 2012-01-01 to 2012-01-10 containing:
  Data: int [1:10, 1] 1 2 3 4 5 6 7 8 9 10
  Indexed by objects of class: [Date] TZ: GMT
  xts Attributes:  
List of 2
 $ tclass: chr "Date"
 $ tzone : chr "GMT"
+1
source

All Articles