Search code examples
rreshape2melt

R: How to create new variable based on name of other column


I would like to create a new variable based on the name of other columns, so that I can move from a wide to a long dataset.

What I have:

df <- data.frame(name = c("1", "2", "3", "4"),
                       alpha_1 = c(50, 30, 20, 6),
                       alpha_2 = c(30, 20, 15, 10),
                       beta_1 = c(50, 30, 20, 6),
                       beta_2 = c(30, 20, 15, 10))

and what I'm hoping to manipulate it into:

df2 <- data.frame(name = c("1", "1", "1", "1", "2", "2", "2", "2","3", "3", "3", "3", "4", "4", 
                            "4", "4"),
                  condition = c(1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2),
                  measure = c("alpha", "alpha", "beta", "beta","alpha", "alpha", "beta", "beta",
                             "alpha", "alpha", "beta", "beta","alpha", "alpha", "beta", "beta"),
                  value = c(50, 30, 50, 30, 30, 20, 30, 20, 20, 15, 20 ,15, 6, 10, 6, 10))

A typical "melt" doesn't work here, as I don't know how to do it based on the column's name. I'd like to do this for all the columns in the dataset. Thanks so much for any help or guidance you can provide!


Solution

  • An option is to pivot into 'long' format and then do the separate

    library(dplyr)
    library(tidyr)
    df %>% 
       pivot_longer(cols = -name, names_to = 'measure') %>%
       separate(measure, into = c('measure', 'condition'))
    #   name measure condition value
    #1     1   alpha         1    50
    #2     1   alpha         2    30
    #3     1    beta         1    50
    #4     1    beta         2    30
    #5     2   alpha         1    30
    #6     2   alpha         2    20
    #7     2    beta         1    30
    #8     2    beta         2    20
    #9     3   alpha         1    20
    #10    3   alpha         2    15
    #11    3    beta         1    20
    #12    3    beta         2    15
    #13    4   alpha         1     6
    #14    4   alpha         2    10
    #15    4    beta         1     6
    #16    4    beta         2    10