gpt4 book ai didi

r - dplyr 如何按组滞后

转载 作者:行者123 更新时间:2023-12-04 12:32:30 25 4
gpt4 key购买 nike

我有一个包含提前期的订单和应收账款数据框。我可以使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com