如何在R中将数据集从宽格式转换为长格式

how to transpose a dataset from wide format to long format in 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

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

提前感谢您的帮助!

SO 上有很多关于重塑的例子。可能是最常见的问题。您所要做的就是搜索。

reshape(data, direction="long", idvar="ID", varying=3:8, sep="")

    ID SEX time bloodpressure weight
1.1  1   1    1            90    100
2.1  2   0    1           101    140
1.2  1   1    2           100    105
2.2  2   0    2           120     NA
1.3  1   1    3            NA    112
2.3  2   0    3           115    150

reshape的帮助页面清楚地解释了sep参数的用法。您也可以尝试使用 tidy 的 pivot_longer 函数。阅读文档。 ;)


数据:

data <- read.table(text="ID SEX bloodpressure1 bloodpressure2 bloodpressure3 weight1 weight2 weight3
1   1     90              100           NA            100     105     112
2   0      101            120          115            140     NA     150", header=TRUE)

使用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