Skip to content

Instantly share code, notes, and snippets.

@thisisnic
Last active November 27, 2018 08:17
Show Gist options
  • Save thisisnic/8df628d8e4134b21bd58e073bc390be9 to your computer and use it in GitHub Desktop.
Save thisisnic/8df628d8e4134b21bd58e073bc390be9 to your computer and use it in GitHub Desktop.
If you have repeated observations in one column, you could transform these into separate rows by using tidyr::separate(), tidyr::gather(), and dplyr::select(). However, in this specific case, tidyr::separate_rows() is a simpler solution!

Code:

library(tidyr)
library(dplyr)
test_scores <- data_frame(student = c("Amy", "Belle", "Candice"),
                          score = c("75-81-86", "77-70-82", "90-91-91"))
test_scores

Output:

# A tibble: 3 x 2
  student score   
  <chr>   <chr>   
1 Amy     75-81-86
2 Belle   77-70-82
3 Candice 90-91-91

Using tidyr::separate(), tidyr::gather(), and dplyr::select()

Code:

separate(test_scores, score, c("score1", "score2", "score3")) %>%
  gather(key, score, -student) %>%
  select(-key)

Output:

# A tibble: 9 x 2
  student score
  <chr>   <chr>
1 Amy     75   
2 Belle   77   
3 Candice 90   
4 Amy     81   
5 Belle   70   
6 Candice 91   
7 Amy     86   
8 Belle   82   
9 Candice 91

Using tidyr::separate_rows()

Code:

separate_rows(test_scores, score)

Output:

# A tibble: 9 x 2
  student score
  <chr>   <chr>
1 Amy     75   
2 Amy     81   
3 Amy     86   
4 Belle   77   
5 Belle   70   
6 Belle   82   
7 Candice 90   
8 Candice 91   
9 Candice 91
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment