Skip to content

Instantly share code, notes, and snippets.

@ginolhac
Created March 3, 2017 19:47
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 ginolhac/3940e106e47a4630f99efefb5ddbc526 to your computer and use it in GitHub Desktop.
Save ginolhac/3940e106e47a4630f99efefb5ddbc526 to your computer and use it in GitHub Desktop.
tidyverse gather
#testdata
v1<-c("color", "red", "red", "red", "red", "green", "green", "green", "green", "yellow", "yellow", "yellow", "yellow", "blue", "blue", "blue", "blue")
v2<-c("year", "2015", "2014", "2013", "2012", "2015", "2014", "2013", "2012", "2015", "2014", "2013", "2012", "2015", "2014", "2013", "2012")
v3<-c("UK", "23", "34", "34", "11", "45", "32", "11", "76", "90", "13", "24", "12", "34", "23", "43", "28")
v4<-c("GER", "95", "43", "21", "43", "57", "22", "52", "34", "52", "56", "76", "90", "23", "78", "4", "12")
v5<-c("POL", "56", "78", "32", "56", "1", "8", "55", "45", "87", "12", "99", "66", "11", "45", "32", "11")
v6<-c("US", "56", "76", "90", "13", "11", "45", "32", "11", "11", "45", "38", "16","54","4","71","67")
df<-as.data.frame(rbind(v1,v2,v3,v4,v5,v6))
df %>%
t() %>% as_tibble() %>%
set_names(nm = .[1,]) %>%
filter(year != "year") %>%
gather(country, value, -color, -year)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment