首页 > 解决方案 > 将数据表列转换为 xts

问题描述

我有一个数据表,现在我想使用数据表语法在 xts 中进行一些计算。我的第一个问题是,如果这通常被推荐,这意味着这两个包是否可以很好地协同工作。另一种方法是将数据表转换为 xts 并在我计划使用 xts 进行转换后将其向后转换。

以下简单的 DT 说明了我的问题:

library(data.table)
dataset <- data.table(ID=c(rep("A",4416),rep("B",4416)),
x = c(rnorm(2208*2)), time=c(seq(as.Date("1988/03/15"),
as.Date("2000/04/16"), "day"),seq(as.Date("1988/03/15"),
as.Date("2000/04/16"), "day")))
dataset

library(xts)
dataset[,x_xts := NULL]
dataset[,x_xts := xts(x,order.by = time),by=ID]
dataset # this looks fine
str(dataset) # this throws an error

1) 你能推荐在数据表中使用 xts 吗?

2)如果不是,您是否建议将数据表转换为 xts 并在之后返回?

为了提供更多信息,我想为面板中的每个单元估计一个 ARIMA 模型,这就是我认为需要使用 xts 的原因。谢谢。

标签: rdatatablexts

解决方案


I think this str(dataset) error it is more related to str than the combination of data.table and xts

If you use the alternative function glimpse from dplyr or make other operations, it works fine:

library(dplyr)
glimpse(dataset)

##Examples
cor(dataset$x,dataset$x_xts)
lm(formula = x~x_xts, data=dataset)
dataset[, A:=x_xts*x]

Anyway, you can also use the as.xts.data.table function if you feel more comfortable that way: https://www.rdocumentation.org/packages/data.table/versions/1.12.0/topics/as.xts.data.table


推荐阅读