使用R将一行与文件中的所有其他行进行比较

时间:2011-09-02 21:41:42

标签: r compare dataframe

我有一个如下文件:

P1 A,B,C    
P2 B,C,D,F    
P3 C,D,E,F  

我需要将每一行与所有其他行进行比较,以获得交叉元素的计数,如下所示:

P1 P2 2    
P1 P3 1    
P2 P3 3   

谢谢你,
小号

2 个答案:

答案 0 :(得分:4)

目前还不清楚原始数据的来源,所以我假设您将数据读入data.frame,如下所示:

x <- data.frame(V1 = c("a", "b", "c"), 
                V2 = c("b", "c", "d"), 
                V3 = c("c", "d", "e"),
                V4 = c(NA, "f", "f"),
                stringsAsFactors = FALSE
                )

row.names(x) <- c("p1", "p2", "p3")

第一步是创建需要比较的所有行的组合:

rowIndices <- t(combn(nrow(x), 2))
> rowIndices
     [,1] [,2]
[1,]    1    2
[2,]    1    3
[3,]    2    3

然后,我们可以将apply中的信息与length()intersect()一起使用,以获得您想要的内容。注意我还索引到data.frame row.names()的{​​{1}}属性,以获得您想要的行名称。

x

给你类似的东西:

data.frame(row1 = row.names(x)[rowIndices[, 1]], 
      row2 = row.names(x)[rowIndices[, 2]],
      overlap = apply(rowIndices, 1, function(y) length(intersect(x[y[1] ,], x[y[2] ,])))
      )

答案 1 :(得分:2)

阅读示例数据。

txt <- "P1 A,B,C
        P2 B,C,D,F
        P3 C,D,E,F"
tc <- textConnection(txt)
dat <- read.table(tc,as.is=TRUE)
close(tc)

转换为长格式并使用自连接和聚合函数。

dat_split <- strsplit(dat$V2,",")
dat_long <- do.call(rbind,lapply(seq_along(dat_split),
            function(x) data.frame(id=x,x=dat_split[[x]], stringsAsFactors=FALSE)))

result <- sqldf("SELECT t1.id AS id1,t2.id AS id2,count(t1.x) AS N 
                 FROM dat_long AS t1  INNER JOIN dat_long AS t2 
                 WHERE (t2.id>t1.id) AND (t1.x=t2.x) GROUP BY t1.id,t2.id")

结果

> result
  id1 id2 N
1   1   2 2
2   1   3 1
3   2   3 3