【问题标题】:R loop to iterate and find unique combination between each itemR循环迭代并找到每个项目之间的唯一组合
【发布时间】:2022-07-12 17:22:59
【问题描述】:
    concept_id                                  concept_name  event
1:     443387                    Malignant tumor of stomach comorb
2:    4193704 Type 2 diabetes mellitus without complication comorb
3:    4095320            Malignant tumor of body of stomach comorb
4:     201826                      Type 2 diabetes mellitus comorb
5:    4174977          Retinopathy due to diabetes mellitus comorb

对于上述数据,我正在尝试为 concept_ids 创建一个组合列表。有 5 个概念 ID,所以当我们用另一个概念 ID 迭代每个概念 ID 时,我们会得到一个类似这样的列表。

nrow(comorb_event)
for (i in (1:nrow(comorb_event))) {
  for (j in (1:nrow(comorb_event))){
    print(paste(i,j))
  }
}

[1] "1 1"
[1] "1 2"
[1] "1 3"
[1] "1 4"
[1] "1 5"
[1] "2 1"
[1] "2 2"
[1] "2 3"
[1] "2 4"
[1] "2 5"
[1] "3 1"
[1] "3 2"
[1] "3 3"
[1] "3 4"
[1] "3 5"
[1] "4 1"
[1] "4 2"
[1] "4 3"
[1] "4 4"
[1] "4 5"
[1] "5 1"
[1] "5 2"
[1] "5 3"
[1] "5 4"
[1] "5 5"

我的输出不是我所期望的。由于项目 [1,1] 是相同的项目,我们可以避免这种情况,同样项目 [2,1] 已经被 [1,2] 覆盖,我们也可以删除它。删除冗余组合后,预期的列表将是这样的:

[1] "1 2"
[1] "1 3"
[1] "1 4"
[1] "1 5"
[1] "2 3"
[1] "2 4"
[1] "2 5"
[1] "3 4"
[1] "3 5"
[1] "4 5"

样本数据

structure(list(concept_id = c("443387", "4193704", "4095320", 
"201826", "4174977"), concept_name = c("Malignant tumor of stomach", 
"Type 2 diabetes mellitus without complication", "Malignant tumor of body of stomach", 
"Type 2 diabetes mellitus", "Retinopathy due to diabetes mellitus"
), event = structure(c(1L, 1L, 1L, 1L, 1L), .Label = c("comorb", 
"drug", "primary_dx"), class = "factor")), class = c("data.table", 
"data.frame"), row.names = c(NA, -5L), .internal.selfref = <pointer: 0x5642431689a0>)

【问题讨论】:

    标签: r loops combinations


    【解决方案1】:

    我们需要combn

    t(combn(seq_len(nrow(comorb_event)), 2))
    

    【讨论】:

    • 如果我想显示concept_ids 的组合而不仅仅是row ids 怎么办?现在我们可以看到行组合(例如:1 2)。我将如何提取concept_ids。而不是 1 2 组合将是 443387 4193704
    • @utsabshrestha 那将是 t(combn(comorb_event$concept_id), 2)) 如果它们不是唯一的,那么在应用 combn 之前用 unique
    猜你喜欢
    • 2018-12-27
    • 2021-04-13
    • 1970-01-01
    • 2020-11-17
    • 1970-01-01
    • 1970-01-01
    • 2021-09-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多