首页 > 解决方案 > 在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但我似乎无法正确使用语法。我完全是新手,这似乎是一个简单的问题。提前致谢。

标签: rdataframedata-manipulation

解决方案


一个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))

推荐阅读