我有以下带有indexClass“Date”的 xts 对象。 index(data)
给了我“POSIXct”对象。我以为index(Data)
会返回一个“Date”对象。
如何从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"
答案 0 :(得分:1)
快速回答:日期没有时区。所以它(我推测)必须将你的日期包装在POSIXct中以保存时区信息。
这是一个没有时区的示例,它显示了您期望的行为:
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"
更新:将tzone属性添加到xts对象不会改变任何内容:
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"
尽管str(x)给出了与你相同的输出:
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"