首页 > 解决方案 > 根据列名的一部分将宽改成长

问题描述

有没有办法根据列名的第一部分在 R 中从宽到长重塑?我有以下数据:

id |  Jan_shoulder | Jan_head | Jan_knee | Feb_shoulder | Feb_head | Feb_knee
1  |     yes       |    no    |    yes   |    no        |   no     |  no
2  |     no        |    no    |    no    |    yes       |   yes    |  no

我想转换它,使每一行对应一个唯一的 id 和月份,例如:

id |  month | shoulder | head | knee 
1  |  Jan   |    yes   |  no  |  yes
1  |  Feb   |    no    |  no  |  no
2  |  Jan   |    no    |  no  |  no
2  |  Feb   |    yes   |  yes |  no

标签: rreshape

解决方案


使用dplyrand tidyr,我们可以gather将数据转换为长格式,将separate列名转换为不同的列,并将spread它们转换为宽格式。

library(dplyr)
library(tidyr)

df %>%
  gather(key, value, -id) %>%
  separate(key, into = c("month", "part"), sep = "_") %>%
  spread(part, value)

#  id month head knee shoulder
#1  1   Feb   no   no       no
#2  1   Jan   no  yes      yes
#3  2   Feb  yes   no      yes
#4  2   Jan   no   no       no

推荐阅读