我无法让xts识别rownames中的时间序列

时间:2015-04-23 20:49:04

标签: r datetime xts

我遇到了xts包的问题。我试图从数据帧创建一个xts。为简单起见,我试图在下面的一个小df上复制我想要做的事情:

> df <- japanTOPIX[,1, drop = FALSE]
> typeof(df[,1])
[1] "double"
> typeof(rownames(df))
[1] "character"
> head(df, 3)
           X7164.JT.Equity
12/27/2000            65.0
12/28/2000            66.5
12/29/2000            66.2
> head(as.Date(rownames(df), format = "%m/%d/%Y"),3)
[1] "2000-12-27" "2000-12-28" "2000-12-29"
> timeBased(as.Date(rownames(df), format = "%m/%d/%Y"))
[1] TRUE
> xts(df, by = as.Date(rownames(df), format = "%m/%d/%Y"))
Error in xts(df, by = as.Date(rownames(df), format = "%m/%d/%Y")) : 
  order.by requires an appropriate time-based object
> head(strptime(rownames(df), format = "%m/%d/%Y"),3)
[1] "2000-12-27 EST" "2000-12-28 EST" "2000-12-29 EST"
> timeBased(strptime(rownames(df), format = "%m/%d/%Y"))
[1] TRUE
> xts(df, by = strptime(rownames(df), format = "%m/%d/%Y"))
Error in xts(df, by = strptime(rownames(df), format = "%m/%d/%Y")) : 
  order.by requires an appropriate time-based object
> head(as.POSIXlt(rownames(df), format = "%m/%d/%Y"),3)
[1] "2000-12-27 EST" "2000-12-28 EST" "2000-12-29 EST"
> timeBased(as.POSIXlt(rownames(df), format = "%m/%d/%Y"))
[1] TRUE
> xts(df, by = as.POSIXlt(rownames(df), format = "%m/%d/%Y"))
Error in xts(df, by = as.POSIXlt(rownames(df), format = "%m/%d/%Y")) : 
  order.by requires an appropriate time-based object
> head(as.POSIXct(rownames(df), format = "%m/%d/%Y"),3)
[1] "2000-12-27 EST" "2000-12-28 EST" "2000-12-29 EST"
> timeBased(as.POSIXct(rownames(df), format = "%m/%d/%Y"))
[1] TRUE
> xts(df, by = as.POSIXct(rownames(df), format = "%m/%d/%Y"))
Error in xts(df, by = as.POSIXct(rownames(df), format = "%m/%d/%Y")) : 
  order.by requires an appropriate time-based object

正如您所看到的,我在尝试创建此xts的每次尝试中都收到错误。包裹声称我不是按时间对象排序,但'by ='变量实际上是基于时间的。任何帮助? (如果示例或代码不清楚,请告诉我,我会尽力澄清。)

编辑:我认为这可能与rownames中的一些非唯一值有关,但事实并非如此:

> nrow(df)
[1] 5115
> length(unique(rownames(df)))
[1] 5115

1 个答案:

答案 0 :(得分:2)

您错误地使用了xts功能。第二个参数应该是order.by而不是by。请参阅以下示例并附上您的数据:

数据:

df <- read.table(text='
           X7164.JT.Equity
12/27/2000            65.0
12/28/2000            66.5
12/29/2000            66.2')

解决方案:

> xts(df, order.by = as.Date(rownames(df), format = "%m/%d/%Y"))
           X7164.JT.Equity
2000-12-27            65.0
2000-12-28            66.5
2000-12-29            66.2

正如您所看到的那样,它可以正常运作!

P.S。您可以使用as.Dateas.POSIXctas.POSIXlt代替strptime。所有这些都正常工作!