使用表 1,我想使用下一年的结果填写“下一个结果”列。有没有一种方法可以在 R 中使用 ID 和次年来处理?
表 1:
ID | 年 | 结果 | 下一个结果 |
---|---|---|---|
123 | 2018 | 更新 | |
123 | 2019 | 取消 | |
123 | 2020 | 更新 |
表 2:
ID | 年 | 结果 | 下一个结果 |
---|---|---|---|
123 | 2018 | 更新 | 取消 |
123 | 2019 | 取消 | 更新 |
123 | 2020 | 更新 | NA |
我可以在 power Bi 或 excel 中做到这一点,但我一直在努力寻找 R 中的解决方案
您可以在
dplyr::lead
中使用mutate
:
library(dplyr)
df %>%
mutate(next_outcome = dplyr::lead(Outcome))
# ID Year Outcome next_outcome
#1 123 2018 Renewed Cancelled
#2 123 2019 Cancelled Renewed
#3 123 2020 Renewed <NA>
数据
df <- read.table(text = "ID Year Outcome
123 2018 Renewed
123 2019 Cancelled
123 2020 Renewed", h = T)