【问题标题】:how to take data relationships and assembles the data into groups based on those relationships in R?如何获取数据关系并根据 R 中的这些关系将数据组合成组?
【发布时间】:2019-04-11 17:32:29
【问题描述】:

我正在尝试匹配数据集中的所有客户,并为那些邮政编码匹配 100%、地址和电子邮件匹配 85% 的客户提供相似的 ID。我可以在R 中使用Record Linkage package 来做到这一点。现在我有这样的结果:

x <- data.frame(ID1=c(1,2, 3, 5, 10, 11, 12), ID2=c(2,5,4,11,11,18,18))

ID1 ID2
1   2
2   5
3   4
5   11
10  11
11  18
12  18

但我想将所有匹配 1,2,5,11,10,12,18 的 ID 组合在一起,所以我想给它们相同的 ID。

基本上我想要这样的输出:

Group   Key
1        1
1        2
1        5
1       11
1       10
1       12
1       18
3        3
3        4

【问题讨论】:

标签: r algorithm


【解决方案1】:

下面的代码给出了我正在寻找的输出:

x

【讨论】:

    【解决方案2】:

    我以前遇到过这个问题,我想知道 R 中是否有快速的解决方案。如果您试图找到将行组合在一起的间隔,可以使用data.table::foverlaps 来做到这一点(请参阅Is it possible to use the R data.table function foverlaps to find the intersection of overlapping ranges in two tables?) ,但是我不熟悉将集合(而不是数字间隔)分组在一起。这是一个解决方案,但它可能不是最快的方法。

        x <- data.frame(ID1=c(1,2, 3, 5, 10, 11, 12), ID2=c(2,5,4,11,11,18,18))
    
    
    sets <- list()
    for(i in 1:nrow(x)){
      temp <- unique(unlist(x[i,]))
      if(length(sets)==0){
        sets[[1]] <- temp
      }else{
        in_sets <- sapply(sets, function(s)any(temp%in%s))  
        if(sum(in_sets)==0){
          sets[[length(sets)+1]] <- temp
        }
        if(sum(in_sets)==1){
          sets[[which(in_sets)]] <- union(sets[[which(in_sets)]],temp)
        }
    
        if(sum(in_sets)>1){
          sets[[which.min(in_sets)]] <-  union(unlist(sets[in_sets]),temp)
          sets[which(in_sets)[-1] ] <-  NULL
        }
    
      }
    
    }
    
    do.call("rbind",mapply(sets,1:length(sets),SIMPLIFY=FALSE,FUN=function(x,n){
      data.frame(Group=n,Key=x)
    }))
    

    【讨论】:

    • 谢谢。您的代码有效。但是我有很大的数据集,所以我想避免循环。我在 R 中找到了一个包,它可以执行此操作,并且运行时间非常短。 library(igraph) y = graph.data.frame(x) z = stack(clusters(y)$membership) 这段代码给出了我正在寻找的输出。
    • 如果您找到了解决方案,您应该回答自己的问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多