【问题标题】:string match all possible variable combinations and output new data frame containing 2 new variables: combination count and strings matched字符串匹配所有可能的变量组合并输出包含 2 个新变量的新数据框:组合计数和匹配的字符串
【发布时间】:2017-12-05 18:40:02
【问题描述】:

拥有此处所述的数据框:

ID <- c(1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3)
String <- c('a', 'b', 'c', 'd', 'a', 'c', 'd', 'e', 'b', 'd', 'e', 'f')

id_data <- data.frame(ID, String)

产生:

ID  String
1     a
1     b
1     c
1     d
2     a
2     c
2     d
2     e
3     b
3     d
3     e
3     f

尝试比较所有可能的 ID 组合以查找与“ID”匹配的“字符串”计数。所需的输出是一个包含四个变量的数据框:
1) 'ID' 变量表示测试的变量

2) 'Count' 变量指示与给定 ID 对匹配的字符串数

2) 'Matched' 变量包含与该特定变量组合匹配的字符串,用逗号分隔。

3) 'Unmatched' 变量包含与该特定 ID 组合不匹配的字符串(也以逗号分隔)。

期望的输出:

 ID  Count   Matched   Unmatched
1-2    3     a, c, d      e
1-3    2     b, d         a, e
2-3    2     d, e         a, c, f

我参考了以下内容,但没有找到满足上述要求的解决方案:

Matching R Data Frames

combn solution

可以在输出中包含重复和自身 ID 组合。

【问题讨论】:

    标签: r


    【解决方案1】:
    do.call(rbind,
            combn(
                x = unique(id_data$ID),
                m = 2,
                FUN = function(x) {
                    temp = id_data[id_data$ID %in% x, ]
                    temp2 = Reduce(intersect, split(temp$String, temp$ID))
                    data.frame(
                        ID = paste(x, collapse = "-"),
                        Count = length(temp2),
                        Matched = toString(temp2),
                        Unmatched = toString(setdiff(temp$String, temp2)))
                },
                simplify = FALSE
            ))
    #    ID Count Matched  Unmatched
    # 1 1-2     3 a, c, d       b, e
    # 2 1-3     2    b, d a, c, e, f
    # 3 2-3     2    d, e a, c, b, f    
    

    【讨论】:

    • 如果你存储split的结果,你可以节省一点工作。如果你unname它,你可以使用do.call而不是Reduce,因为它的长度总是和m一样。
    • 不错。谢谢,d.b.适用于相对较小的数据集,但存在扩展问题。我可能会尝试对程序进行“分段”,看看是否有帮助(欢迎提出建议)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-04
    相关资源
    最近更新 更多