r - dplyr 如何按组滞后

标签 r dplyr

我有一个包含提前期的订单和应收账款数据框。 我可以使用 dplyr 根据组提前期填写接收栏吗?

df <- data.frame(team = c("a","a","a","a", "a", "b", "b", "b", "b", "b"),
                 order     = c(2, 4, 3, 5, 6, 7, 8, 5, 4, 5),
                 lead_time = c(3, 3, 3, 3, 3, 2, 2, 2, 2, 2))
>df
   team order lead_time
     a     2         3
     a     4         3
     a     3         3
     a     5         3
     a     6         3
     b     7         2
     b     8         2
     b     5         2
     b     4         2
     b     5         2

然后像这样添加一个接收列:

dfb <- data.frame(team = c("a","a","a","a", "a", "b", "b", "b", "b", "b"),
                 order     = c(2, 4, 3, 5, 6, 7, 8, 5, 4, 5),
                 lead_time = c(3, 3, 3, 3, 3, 2, 2, 2, 2, 2), 
                 receive = c(0, 0, 0, 2, 4, 0, 0, 7, 8, 5))

>dfb
team order lead_time receive
    a     2         3       0
    a     4         3       0
    a     3         3       0
    a     5         3       2
    a     6         3       4
    b     7         2       0
    b     8         2       0
    b     5         2       7
    b     4         2       8
    b     5         2       5

我是这么想的,但是遇到了错误

dfc <- df %>%
      group_by(team) %>%
      mutate(receive = if_else( row_number() < lead_time, 0, lag(order, n = lead_time)))

Error in mutate_impl(.data, dots) : 
  could not convert second argument to an integer. type=SYMSXP, length = 1

感谢您的帮助!

最佳答案

这看起来像一个错误; dplyrstats 包之间的 lag 函数可能有一些意外的掩码,请尝试解决此问题:

df %>% 
    group_by(team) %>% 
    # explicitly specify the source of the lag function here
    mutate(receive = dplyr::lag(order, n=unique(lead_time), default=0))

#Source: local data frame [10 x 4]
#Groups: team [2]

#     team order lead_time receive
#   <fctr> <dbl>     <dbl>   <dbl>
#1       a     2         3       0
#2       a     4         3       0
#3       a     3         3       0
#4       a     5         3       2
#5       a     6         3       4
#6       b     7         2       0
#7       b     8         2       0
#8       b     5         2       7
#9       b     4         2       8
#10      b     5         2       5

关于r - dplyr 如何按组滞后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43772134/

相关文章:

r - 如何解决 R 中的简单优化

R:添加一个 dplyr 组标签作为数字

r - 由于 .key 已被弃用,如何在 nest() 中重命名数据列?

r - ggplot2 扩展和附加包

Emacs 中的 r-autoyas

r - 如何使用 transmute_if/transmute_at 实现大标题除以列

r - 我可以让这个 dplyr + data.table 任务更快吗?

r - 使用 JAGS 的贝叶斯广义泊松零一技巧

r - 通过 dplyr 中的主题 ID 和匹配序列 ID 连接两个数据集

r - 如果在 2 行中满足某些条件,如何在 R 数据框中添加新列以显示当前行和前一行中值的总和?