首页 > 解决方案 > 如何在R中将数据集从宽格式转换为长格式

问题描述

数据集类似于以下内容:

ID SEX bloodpressure1 bloodpressure2 bloodpressure3 weight1 weight2 weight3
1   1     90              100           NA            100     105     112
2   0      101            120          115            140     NA     150

*有超过200个变量

我希望输出如下:

ID SEX n bloodpressure weight
1   1  1      90        100
1   1  2      100       105
1   1  3      NA        112
2   0  1      101       140
2   0  2      120       NA
2   0  3      115       150

我尝试了此链接中提供的解决方案: Using Reshape from wide to long in R 但由于我的数据集中的变量名在字母和数字之间没有“_”,我不知道如何分隔列名来制作它工作。

预先感谢您的任何帮助!

标签: rreshapetranspose

解决方案


使用tidyr::pivot_longer

tidyr::pivot_longer(df, cols = -c(ID, SEX), 
                   names_to = c('.value', 'n'), 
                   names_pattern = '(.*)(\\d+)')

# A tibble: 6 x 5
#     ID   SEX n     bloodpressure weight
#  <int> <int> <chr>         <int>  <int>
#1     1     1 1                90    100
#2     1     1 2               100    105
#3     1     1 3                NA    112
#4     2     0 1               101    140
#5     2     0 2               120     NA
#6     2     0 3               115    150

推荐阅读