Skip to content

Instantly share code, notes, and snippets.

@danweitzel
Last active February 4, 2021 20:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danweitzel/4b8a28e1005612282ee5d9f42cbb42c2 to your computer and use it in GitHub Desktop.
Save danweitzel/4b8a28e1005612282ee5d9f42cbb42c2 to your computer and use it in GitHub Desktop.
Change indicator
## Load the library
library("tidyverse")
## Generate a fake data set with two countries, six years, and a changing indicator
df <- tibble(country = rep(c("A", "B"), each = 6),
year = rep(seq(1:6), times = 2),
ind = c(1,1,2,1,2,1,1,1,1,1,2,1))
## Make a dummy called 'changed' that is TRUE when 'ind' changed in the last three years and FALSE otherwise
## Working with rowMeans calculation, assuming that NA indicates NO change
df <-
df %>%
group_by(country) %>%
arrange(country, year) %>%
mutate(ind_l1 = lag(ind, n = 1),
ind_l2 = lag(ind, n = 2)) %>%
ungroup %>%
mutate(changed = ifelse(rowMeans(select(., starts_with("ind")), na.rm = TRUE) == ind, FALSE, TRUE))
@danweitzel
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment