Skip to content

Instantly share code, notes, and snippets.

@thisisnic
Last active November 23, 2018 15:05
Show Gist options
  • Save thisisnic/73d9cfc761b4501ae47492220cc7c267 to your computer and use it in GitHub Desktop.
Save thisisnic/73d9cfc761b4501ae47492220cc7c267 to your computer and use it in GitHub Desktop.
A lesser-known dplyr function: lag(). Use lag() to get the previous value in a vector. The equivalent for getting the next value is lead(). I've not used them often, but when I have they've saved me from writing horrible workarounds!

Code:

library(dplyr)
BOD

Output:

  Time demand
1    1    8.3
2    2   10.3
3    3   19.0
4    4   16.0
5    5   15.6
6    7   19.8

Code:

mutate(BOD, change = demand - lag(demand))

Output:

  Time demand change
1    1    8.3     NA
2    2   10.3    2.0
3    3   19.0    8.7
4    4   16.0   -3.0
5    5   15.6   -0.4
6    7   19.8    4.2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment