XTS 不将日期时间识别为适当的基于时间的对象

XTS does not recognize datetime as an appropriate time-based object

我正在使用 R。我有一些值和一个日期时间索引。我想在 xts 中转换 tibble。

这是示例数据和我使用的代码:

Date <- c("2010-01-04" , "2010-01-04")
Time <- c("04:00:00", "06:00:00")
value <- c(1, 2)          
df <- as_tibble(value) %>% add_column(Date = Date, Time = Time)
df <- df %>% mutate(datetime = as.POSIXct(paste(Date, Time), format="%Y-%m-%d %H:%M:%S"))

library(xts)
dfxts <- as.xts(df[,1], order.by=df[,4])

然而,我收到以下错误:

Error in xts(x, order.by = order.by, frequency = frequency, ...) : 
    order.by requires an appropriate time-based object

知道是什么原因造成的吗? Datetime 应该是一个合适的基于时间的对象...非常感谢。

order_by 的参数必须是向量。当您使用 foo[,bar]tbl_df 中提取时,返回对象的 class 不是向量,而是 tbl_df。使用 df[[4]].

您应该 re-examine 每一步并检查您得到了什么。实际上,我发现在 one 容器中最容易做到这一点。你可以用tbl,我正好喜欢data.frame

所以让我们首先根据您的数据构建一个 data.frame

R> Date <- c("2010-01-04" , "2010-01-04")
R> Time <- c("04:00:00", "06:00:00")
R> value <- c(1, 2)
R> df <- data.frame(Date=Date, Time=Time, value=value)
R> df
        Date     Time value
1 2010-01-04 04:00:00     1
2 2010-01-04 06:00:00     2
R> 

然后让我们整理并解析日期和时间信息并进行检查:

R> df[,"pt"] <- as.POSIXct(paste(Date, Time))
R> df
        Date     Time value                  pt
1 2010-01-04 04:00:00     1 2010-01-04 04:00:00
2 2010-01-04 06:00:00     2 2010-01-04 06:00:00
R> 

之后只需使用正确的组件调用 xts

R> x <- xts(df[,"value"], order.by=df[,"pt"])
R> x
                    [,1]
2010-01-04 04:00:00    1
2010-01-04 06:00:00    2
R> 

编辑 或者您可以一步完成所有操作 无需任何其他包 但放弃逐步执行中间步骤的能力:

R> x2 <- xts(value, order.by=as.POSIXct(paste(Date, Time)))
R> x2
                    V1
2010-01-04 04:00:00  1
2010-01-04 06:00:00  2
R> all.equal(x, x2)
[1] TRUE
R>