Last active
September 25, 2017 13:08
-
-
Save safferli/eb81a0fc3384f855c2f3c2d7056d6f9c to your computer and use it in GitHub Desktop.
Clean messed up wide/long format
This file contains hidden or 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
library(tibble) | |
library(dplyr) | |
library(tidyr) | |
# generate dataset | |
dta <- tibble::data_frame( | |
Land = c(rep("Bahamas", 4), "Bahrein"), | |
Year = c(rep(c(1999, 2000), 2), 1999), | |
indicator1 = c(5, 6, NA, NA, NA), | |
indicator2 = c(5, 8, NA, NA, NA), | |
indicator3 = c(NA, NA, 7, 8, NA) | |
) | |
# do cleaning here | |
dta %>% | |
# go from "wide" to "long" format | |
gather(indicator, value, -Land, -Year) %>% | |
# remove NA values | |
na.omit() %>% | |
# spread it back into "wide" format | |
spread(indicator, value) %>% | |
dplyr::right_join( | |
expand.grid(Land = unique(dta$Land), Year = unique(dta$Year), stringsAsFactors = FALSE) | |
) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Neue Version, neues Ergebnis!