Search code examples
rreshape

Gather multiple columns into one key and two values


I need to gather multiple columns into one key and two values. I encountered a lot of similar questions here, but i cannot reproduce the answers since they were very specific and not well explained imho. If there is one, which answers my question, i´m happy with a link.

Example df:

df <- data.frame(semester=rep(1:6),
                 Anna_try1=c(1,2,2,1,4,2),
                 Lena_try1=c(3,4,2,3,2,1),
                 Anna_try2=c(2,3,1,2,1,4),
                 Lena_try2=c(2,4,2,1,5,2))

which looks like this:

enter image description here

And i need something like this:

enter image description here


Solution

  • Try reshaping to long, separate the variables into desired new values and then reshape to wide. Here the code using tidyverse functions:

    library(tidyverse)
    #Code
    df <- df %>% pivot_longer(-semester) %>%
      separate(name,c('name','try'),sep = '_') %>%
      mutate(try=paste0('grade_',try)) %>%
      pivot_wider(names_from = try,values_from=value) %>%
      arrange(name,semester)
    

    Output:

    # A tibble: 12 x 4
       semester name  grade_try1 grade_try2
          <int> <chr>      <dbl>      <dbl>
     1        1 Anna           1          2
     2        2 Anna           2          3
     3        3 Anna           2          1
     4        4 Anna           1          2
     5        5 Anna           4          1
     6        6 Anna           2          4
     7        1 Lena           3          2
     8        2 Lena           4          4
     9        3 Lena           2          2
    10        4 Lena           3          1
    11        5 Lena           2          5
    12        6 Lena           1          2