r - 在R中的数据框中合并几乎相同的行
问题描述
我有一个大的临床数据数据框(154 个变量的 882 个 obs)。在这个数据框中,有 441 名独特的患者,重复两次,除了一列。因此,该表的虚拟版本如下所示:
ID | 年龄 | 性别 | 瘤 | 类型 | 治疗 |
---|---|---|---|---|---|
1 | 76 | F | 冒号 | 腺苷 | 放射治疗 |
1 | 76 | F | 冒号 | 腺苷 | 化疗 |
2 | 70 | 米 | 冒号 | 腺苷 | 放射治疗 |
2 | 70 | 米 | 冒号 | 腺苷 | 化疗 |
3 | 68 | 米 | 冒号 | 腺苷 | 放射治疗 |
3 | 68 | 米 | 冒号 | 腺苷 | 化疗 |
我想把这张表压缩成这样:
ID | 年龄 | 性别 | 瘤 | 类型 | 治疗_a | 治疗_b |
---|---|---|---|---|---|---|
1 | 76 | F | 冒号 | 腺苷 | 放射治疗 | 化疗 |
2 | 70 | 米 | 冒号 | 腺苷 | 放射治疗 | 化疗 |
3 | 68 | 米 | 冒号 | 腺苷 | 放射治疗 | 化疗 |
我在网上查看并尝试使用类似问题的解决方案,例如。sapply
, group_by
, summarise
,distinct
但我似乎无法正确使用语法。我完全是新手,这似乎是一个简单的问题。提前致谢。
解决方案
一个data.table
选项使用dcast
dcast(
setDT(df)[,q := paste0(treatment,"_",head(letters,.N)),id:type],
...~ q,
value.var = "treatment")
给
id age gender tumour type chemotherapy_b radiotherapy_a
1: 1 76 F colon adeno chemotherapy radiotherapy
2: 2 70 M colon adeno chemotherapy radiotherapy
3: 3 68 M colon adeno chemotherapy radiotherapy
数据
> dput(df)
structure(list(id = c(1L, 1L, 2L, 2L, 3L, 3L), age = c(76L, 76L,
70L, 70L, 68L, 68L), gender = c("F", "F", "M", "M", "M", "M"),
tumour = c("colon", "colon", "colon", "colon", "colon", "colon"
), type = c("adeno", "adeno", "adeno", "adeno", "adeno",
"adeno"), treatment = c("radiotherapy", "chemotherapy", "radiotherapy",
"chemotherapy", "radiotherapy", "chemotherapy")), class = "data.frame", row.names = c(NA,
-6L))
推荐阅读
- python - Pandas groupby 有条件地查找 timedelta 列的平均值
- excel - 使用 Excel VBA 从不同工作簿引用索引/匹配公式中的文件路径变量
- xamarin.forms - Xamarin.Forms 使用 SQLite - 如何更新特定列的所有数据?
- c# - ASP.net core 3.1 List 填充在 onGet 但不在 OnPost 中。绑定它的正确方法是什么?
- java - 杰克逊在序列化过程中添加了不存在的字段
- google-cloud-platform - 取消 GCP 数据存储中的字段索引,以提高性能(调整数据存储)
- python - 如何创建为提到的用户赋予角色的机器人命令 | 不和谐.py
- objective-c - Objective-C - 如何打开 .csv 文件?
- c - 如何使用内核哈希表 API?
- java - 使用布尔值从用户字符串 java 输入验证