【问题标题】:Efficient way of row binding time series in a data.table, with correctly sorted timestampsdata.table 中行绑定时间序列的有效方式,时间戳正确排序
【发布时间】:2018-05-31 00:57:03
【问题描述】:

有没有更有效的方法来行绑定(或有效合并)两个或更多大型时间序列与数据表?时间序列有一些不同的列,所以我使用fill = TRUE

我希望每个时间序列中的所有行都出现在最终的 data.table 中。我可以在下面做,但是时间序列戳没有在下面的dt3 中排序。我必须创建dt4 才能获得订购的邮票。

我想知道是否有更有效的方法在 data.table 中进行一种 rbind/时间序列合并?

library(data.table)

tm <- seq(as.POSIXct("2018-05-12 00:00"), as.POSIXct("2018-05-14"), by = "hours")
dt <- data.table(time = tm, x = seq(1, length(tm), by = 1))

set.seed(1)

dt2 <- data.table(time = tm[sample(length(tm), size = 8)] + rnorm(n = 8, 0, 60),
                 y = rnorm(8))

# Can a one liner here get me the output in `dt4` with some kind of row bind? 
#  Is there a way to do a row bind here instead that avoids the creation of a new object dt4 that takes the sorted rows?

dt3 <- rbind(dt, dt2, fill = TRUE)

dt4 <- dt3[order(time)]

                      tail(dt4, 20)
#                   time  x           y
# 1: 2018-05-13 08:00:00 33          NA
# 2: 2018-05-13 09:00:00 34          NA
# 3: 2018-05-13 10:00:00 35          NA
# 4: 2018-05-13 11:00:00 36          NA
# 5: 2018-05-13 12:00:00 37          NA
# 6: 2018-05-13 13:00:00 38          NA
# 7: 2018-05-13 14:00:00 39          NA
# 8: 2018-05-13 14:59:41 NA  0.94383621
# 9: 2018-05-13 15:00:00 40          NA
# 10: 2018-05-13 16:00:00 41          NA
# 11: 2018-05-13 16:01:30 NA  0.82122120
# 12: 2018-05-13 17:00:00 42          NA
# 13: 2018-05-13 17:00:44 NA -0.04493361
# 14: 2018-05-13 18:00:00 43          NA
# 15: 2018-05-13 19:00:00 44          NA
# 16: 2018-05-13 20:00:00 45          NA
# 17: 2018-05-13 21:00:00 46          NA
# 18: 2018-05-13 22:00:00 47          NA
# 19: 2018-05-13 23:00:00 48          NA
# 20: 2018-05-14 00:00:00 49          NA

【问题讨论】:

  • 我可以知道为什么它必须是 1-liner 吗?也许rbindlist(list(dt,dt2), fill=TRUE)[order(time)]?而在R语言中,merge这个词更像sql-join(左右表,而不是上下)。见?merge
  • 时间序列真的很大。每个系列中有 10+ 百万行。想知道是否有比我建议的更好的方法,因为我在循环中多次执行此操作。我担心dt3[order(time)] 在已经执行 rbind 之后可能是一项昂贵的操作?在xts id 中只需执行merge,它会自动处理合并中的排序
  • 我在寻找的东西在某种意义上就像一个外部合并
  • 感谢 dww。你为什么不把它作为答案。我以为我在订购时过于复杂了。

标签: r data.table


【解决方案1】:

如果您将时间列设置为键

setkey(dt, time)
setkey(dt2, time)

那么你可以使用merge.data.table

merge(dt,dt2,all=TRUE)

注意,如果已知时间序列已排序(其中 dt 是,但 dt2 不是),您可以通过设置 data.tables 的 'sorted' 属性来加快速度,而不是调用setkey.

attr(dt, 'sorted') = 'time'

【讨论】:

  • 感谢属性排序提示。我在哪里可以阅读有关 data.table 的“技巧”?专门针对时间序列问题
  • hmmm - 我不确定我是否在任何地方看到过 attr 技巧。总的来说,cran.r-project.org/web/packages/data.table/vignettes/… 是一个很好的资源
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-05-02
  • 2016-05-18
  • 2018-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-07
相关资源
最近更新 更多