Skip to content

Instantly share code, notes, and snippets.

@clayford
Last active March 6, 2020 19:55
Show Gist options
  • Save clayford/3803e2bd8c0211e167d435bcbe2db5d8 to your computer and use it in GitHub Desktop.
Save clayford/3803e2bd8c0211e167d435bcbe2db5d8 to your computer and use it in GitHub Desktop.
pivot_longer versus gather
library(tidyverse)
d1 <- tibble(name = c("Clay", "Laura"),
score_1 = c(88, 99),
score_2 = c(77, 88),
score_3 = c(55, 66),
survey_1 = c(4, 5),
survey_2 = c(3, 3),
survey_3 = c(2, 5))
d1
# A tibble: 2 x 7
# name score_1 score_2 score_3 survey_1 survey_2 survey_3
# <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#1 Clay 88 77 55 4 3 2
#2 Laura 99 88 66 5 3 5
# Let's say we want this.
# name id score survey
# 1 Clay 1 88 4
# 2 Clay 2 77 3
# 3 Clay 3 55 2
# 4 Laura 1 99 5
# 5 Laura 2 88 3
# 6 Laura 3 66 5
# gather - takes two steps plus a join
r1 <- d1 %>%
select(name, starts_with("score")) %>%
gather(key = "id", value = "score", -name) %>%
mutate(id = str_extract(id, "[0-9]"))
r2 <- d1 %>%
select(name, starts_with("survey")) %>%
gather(key = "id", value = "survey", -name) %>%
mutate(id = str_extract(id, "[0-9]"))
d_long <- left_join(r1, r2, by = c("name", "id")) %>%
arrange(name, id)
d_long
# A tibble: 6 x 4
# name id score survey
# <chr> <chr> <dbl> <dbl>
#1 Clay 1 88 4
#2 Clay 2 77 3
#3 Clay 3 55 2
#4 Laura 1 99 5
#5 Laura 2 88 3
#6 Laura 3 66 5
# pivot_longer - all-in-one, though a little abstract!!
pivot_longer(d1,
-name,
names_to = c(".value", "id"),
names_sep = "_")
# A tibble: 6 x 4
# name id score survey
# <chr> <chr> <dbl> <dbl>
#1 Clay 1 88 4
#2 Clay 2 77 3
#3 Clay 3 55 2
#4 Laura 1 99 5
#5 Laura 2 88 3
#6 Laura 3 66 5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment