假设我有一个df
这样的人
Dealer Period Revenue
A August 10
B August 10
A September 30
B September 5
如何使用mutate函数创建一列,以显示收入与上一期间的比较结果。
我想要的结果是类似的
Dealer Period Revenue Compared_result
A August 10 N/A
B August 10 N/A
A September 30 20
B September 5 -5
答案 0 :(得分:2)
library(dplyr)
df %>% group_by(Dealer) %>%
mutate(Comp=Revenue-lag(Revenue))
# A tibble: 4 x 4
# Groups: Dealer [2]
Dealer Period Revenue Comp
<fct> <fct> <int> <int>
1 A August 10 NA
2 B August 10 NA
3 A September 30 20
4 B September 5 -5