突变列显示与上一时期相比的增/减值

时间:2018-08-07 06:43:06

标签: r dplyr

假设我有一个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

1 个答案:

答案 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