gpt4 book ai didi

r - 在 R 和 dplyr 中按组滞后/领先

转载 作者:行者123 更新时间:2023-12-04 13:58:26 26 4
gpt4 key购买 nike

我在尝试延迟按团队分组的日期时遇到问题。

数据:

 df <- data.frame(Team = c("A", "A", "A", "A", "B", "B", "B", "C", "C", "D", "D"),
Date = c("2016-05-10","2016-05-10", "2016-05-10", "2016-05-10",
"2016-05-12", "2016-05-12", "2016-05-12",
"2016-05-15","2016-05-15",
"2016-05-30", "2016-05-30"),
Points = c(1,4,3,2,1,5,6,1,2,3,9)
)

Team Date Points
A 2016-05-10 1
A 2016-05-10 4
A 2016-05-10 3
A 2016-05-10 2
B 2016-05-12 1
B 2016-05-12 5
B 2016-05-12 6
C 2016-05-15 1
C 2016-05-15 2
D 2016-05-30 3
D 2016-05-30 9

预期结果:
Team      Date       Points   Date_Lagged
A 2016-05-10 1 NA
A 2016-05-10 4 NA
A 2016-05-10 3 NA
A 2016-05-10 2 NA
B 2016-05-12 1 2016-05-10
B 2016-05-12 5 2016-05-10
B 2016-05-12 6 2016-05-10
C 2016-05-15 1 2016-05-12
C 2016-05-15 2 2016-05-12
D 2016-05-30 3 2016-05-15
D 2016-05-30 9 2016-05-15

在我意识到以下不是正确的解决方案后,我摸不着头脑:
df %>% group_by(Date) %>% mutate(Date_lagged = lag(Date))  

知道如何修复它吗?

最佳答案

lag默认偏移为 n=1 .但是,我们有“团队”和“日期”的重复元素。为了得到预期的输出,我们需要得到 distinct 'Team', 'Date' 行,用 lag 创建一个 'Date_lagged' '日期' 和 right_join (或 left_join )与原始数据集。

distinct(df, Team, Date) %>%
mutate(Date_Lagged = lag(Date)) %>%
right_join(., df) %>%
select(Team, Date, Points, Date_Lagged)
# Team Date Points Date_Lagged
#1 A 2016-05-10 1 <NA>
#2 A 2016-05-10 4 <NA>
#3 A 2016-05-10 3 <NA>
#4 A 2016-05-10 2 <NA>
#5 B 2016-05-12 1 2016-05-10
#6 B 2016-05-12 5 2016-05-10
#7 B 2016-05-12 6 2016-05-10
#8 C 2016-05-15 1 2016-05-12
#9 C 2016-05-15 2 2016-05-12
#10 D 2016-05-30 3 2016-05-15
#11 D 2016-05-30 9 2016-05-15

或者我们也可以
df %>% 
mutate(Date_Lagged = rep(lag(unique(Date)), table(Date)))

关于r - 在 R 和 dplyr 中按组滞后/领先,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37993855/

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