【问题标题】:recycle vector values with data.table shift instead of padding with fill=NA使用 data.table 移位回收向量值,而不是使用 fill=NA 填充
【发布时间】:2018-11-15 03:02:11
【问题描述】:

我想使用data.table 中的shift 函数来领先/滞后一个新列,但我想从添加到data.table 的滞后向量中回收值。据我所知,fill must be a vector of length 1,因此滞后的值必须填充一个常量值(即这里的NA)。

请参阅下面的 MWE。

dt1 是使用 shift 函数的结果 data.table。新的 b 列具有 NA 值,应该是 4、5 和 6。

dt2 是所需的 data.table 结果。如果我的想法是正确的,则输出需要R 回收规则,但指定了向量应该从哪里开始的超前/滞后值。

我本可以添加一个新向量(请参阅下面的 x_to_avoid),但这需要更多我希望避免的手动工作。

谢谢,

library(data.table)
library(magrittr)

# vector to lead/lag when updating datatable
x = c(1:6)

# leaves NA where 4, 5, 6 "should" have gone for my purposes
dt1 <- data.table(a = c(1:10)) %>% 
  .[, b := shift(x,
                 n = 3L,
                 fill = NA,
                 type = c("lag"))]
dt1

# desired output
dt2 <- dt1[, .(a)] %>% 
  .[, b := c(4,5,6,1,2,3,4,5,6,1)]

# could use another vector, but my actual use is more complicated and I prefer to avoid this (if possible)
x_to_avoid = c(4,5,6,1:6,1)

【问题讨论】:

  • 也许你可以定义你自己的函数,比如shift2 &lt;- function(x, n, type = "lag") if(type == "lag") c(tail(x, -(length(x) - n)), head(x, -n)) else c(tail(x, -n), head(x, -(length(x) - n)))。然后你可以做dt1 &lt;- data.table(a = 1:10, b = shift2(x, n = 3L))。虽然这里的n 不像data.table::shift 那样矢量化
  • @DavidArenburg 谢谢。不熟悉headtail 功能。也不知道如何定义没有{ 括号的函数!速度在这里不是一个大问题,因为它是一次性的,我可能会创建一个 CSV 文件来加载(因此其他人可以使用它)。这太棒了,谢谢!如果您将其发布为答案,我会将其标记为正确(如果您愿意)...
  • 我不会做一些破解作为官方 data.table 答案。我认为您或许可以在 GH issues 页面上添加功能请求。

标签: r data.table


【解决方案1】:

我认为binhf::shift 可以胜任。首先,您需要使用rep.len 延长矢量,然后您可以使用binhf::shift 循环它。不过我不知道性能。

【讨论】:

    猜你喜欢
    • 2018-10-06
    • 1970-01-01
    • 2012-02-19
    • 1970-01-01
    • 2013-07-15
    • 2013-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多