3

我有以下带有 indexClass“日期”的xts对象。index(data)给了我“POSIXct”对象。我认为index(Data)会返回一个“日期”对象。

如何从中获取“日期”对象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"
4

1 回答 1

1

快速回答:日期没有时区。所以它(我想)必须将您的 Date 包装在 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"
于 2012-05-13T06:40:09.107 回答