Last active
February 4, 2021 20:58
-
-
Save danweitzel/4b8a28e1005612282ee5d9f42cbb42c2 to your computer and use it in GitHub Desktop.
Change indicator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## 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)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In response to: https://twitter.com/hilango/status/1357396357573656576