rdataframemutatedata-transform

How do I create a new column in my DF of daily measurements that gives me the increase between today's and yesterday's measurement?


I have a column of datapoints for daily measurements in my DF. I would like to add a new column to said DF that tells me the increase or decrease of this measurement in comparison to yesterday's.

Basically by how much the measurement increased since yesterday.

I have:

# A tibble: 6 × 1
  measurement
       <dbl>
1          1
2          2
3          3
4          5
5          7
6         10

And I want:

# A tibble: 6 × 2
  measurement increase
       <dbl>    <dbl>
1          1       NA
2          2        1
3          3        1
4          5        2
5          7        2
6         10        3

I would expect something like this to work:

DF2 <- DF |> mutate(increase = measurement - measurement[])

I do, however, not know what to put inside the [] in order to tell R to take the previous rows value.


Solution

  • Use diff()

    mutate(df, increase = c(NA, diff(measurement)))
    

    Output:

      measurement increase
            <dbl>    <dbl>
    1           1       NA
    2           2        1
    3           3        1
    4           5        2
    5           7        2
    6          10        3