r - 如何在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 但由于我的数据集中的变量名在字母和数字之间没有“_”,我不知道如何分隔列名来制作它工作。
预先感谢您的任何帮助!
解决方案
使用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
推荐阅读
- docker - 更改 openshift 命名空间的节点选择器的注释
- xaml - 是否有可以在我的应用程序中使用的标准 UWP“符号和特殊字符”对话框?
- cakephp - cakephp 2.4.6 和数组输出
- html - 错误:初始化后无法更改选择的“多重”模式
- sql-server - Where Caluse 中 SQL 中的 TOP 子句
- ios - UISearchBar 似乎返回正确的计数,但不是正确的行
- angular - 用户单击“添加记录”按钮时如何添加记录
- javascript - 类型错误:使用 ftp-deploy 时无法读取未定义的属性“减少”
- java - PDFBox PDFMergerUtility 在 JavaFX 应用程序上不稳定
- sql - SQL:使用连接选择右表中的记录计数