R:如何根据其他列的名称创建新变量

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

我想根据其他列的 name 创建一个新变量,这样我就可以从宽数据集转移到长数据集。

我有:

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))

以及我希望将其操纵成的内容:

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))

典型的 "melt" 在这里不起作用,因为我不知道如何根据列的名称来做。我想对数据集中的所有列执行此操作。非常感谢您提供的任何帮助或指导!

一个选项是转换为 'long' 格式,然后执行 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