Search code examples
rdataframesubtraction

Subtract next value from present R


What I want to do in my dataframe is create a new column with the value from the subtraction of the present value (n), subtracted to the next value (n + 1), so it is: (n + 1) - (n).

The diff() command does the (n) - (n - 1).

For example:

Id  Value   Diff    Diff_Wanted
1   120     NA      2
2   122     2       3
3   125     3       3
4   128     3       6
5   134     6       6
6   140     6       12
7   152     12      8
8   160     8       NA

Diff_Wanted is the desired column to be added in the data frame.


Solution

  • library(dplyr)
    df %>% mutate(Diff_Wanted = lead(Value - lag(Value)))
    # A tibble: 8 x 4
         Id Value  Diff Diff_Wanted
      <dbl> <dbl> <dbl>       <dbl>
    1     1   120    NA           2
    2     2   122     2           3
    3     3   125     3           3
    4     4   128     3           6
    5     5   134     6           6
    6     6   140     6          12
    7     7   152    12           8
    8     8   160     8          NA