R通过拆分列名将df从宽转换为long

时间:2018-03-19 09:32:15

标签: r tidyr

我正在尝试将以下df_original data.frame转换为df_goal中的表单。原始data.frame中的列应分开,后一部分用作键,而第一部分应保留为变量名。我最好使用tidyverse解决方案,但对每一个方法都是开放的。非常感谢你!

df_original <- 
  data.frame(id = c(1,2,3),
           variable1_partyx = c(4,5,6),
           variable1_partyy = c(14,15,16),
           variable2_partyx = c(24,25,26),
           variable2_partyy = c(34,35,36))

df_goal <- 
  data.frame(id = c(1,1,2,2,3,3),
             key = c("partyx","partyy","partyx","partyy","partyx","partyy"),
             variable1 = c(4,14,5,15,6,16),
             variable2 = c(24,34,25,35,26,36))

1 个答案:

答案 0 :(得分:2)

df_original %>%
  tidyr::gather(key, value, -id) %>%
  tidyr::separate(key, into = c("var", "key"), sep = "_") %>%
  tidyr::spread(var, value)