dplyr如何落后于群体

时间:2017-05-04 00:52:13

标签: 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

感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

这看起来像一个bug;在lagdplyr包之间可能存在stats函数的某些意外掩码,请尝试以下方法:

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

答案 1 :(得分:2)

我们也可以使用CBPeripheralManagerDelegate

中的shift
data.table
相关问题