Take Running Difference by Group and Multiple Columns

前端 未结 1 1712
心在旅途
心在旅途 2021-01-27 23:47

I have a dataframe like below:

Date <- as.Date(c(\'2017-10-16\',
                  \'2017-10-16\',
                  \'2017-10-17\',
                  \'2017         


        
相关标签:
1条回答
  • 2021-01-28 00:09

    A solution using dplyr. We can use mutate_at to specify the columns to conduct operations. lag can change the position of the values for the calculation.

    library(dplyr)
    
    df2 <- df %>%
      group_by(Date) %>%
      mutate_at(vars(-Source), funs(Diff = . - lag(.))) %>%
      ungroup()
    df2
    
    # # A tibble: 10 x 6
    #          Date     Source Revenue   Cost Revenue_Diff Cost_Diff
    #        <date>     <date>   <dbl>  <dbl>        <dbl>     <dbl>
    #  1 2017-10-16 2017-11-29  206.88 100.88           NA        NA
    #  2 2017-10-16 2017-11-30  210.88  10.88            4       -90
    #  3 2017-10-17 2017-11-29  194.13  85.13           NA        NA
    #  4 2017-10-17 2017-11-30  200.13 100.13            6        15
    #  5 2017-10-18 2017-11-29  170.00 170.00           NA        NA
    #  6 2017-10-18 2017-11-30  170.00 100.00            0       -70
    #  7 2017-10-19 2017-11-29  746.65  46.65           NA        NA
    #  8 2017-10-19 2017-11-30  736.65  50.65          -10         4
    #  9 2017-10-20 2017-11-29  772.00  23.00           NA        NA
    # 10 2017-10-20 2017-11-30  772.00  24.00            0         1
    
    0 讨论(0)
提交回复
热议问题