【问题标题】:Compare one row to all other rows in a file using R使用 R 将一行与文件中的所有其他行进行比较
【发布时间】:2011-09-02 21:41:42
【问题描述】:

我有一个如下文件:

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

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

P1 P2 2    
P1 P3 1    
P2 P3 3   

谢谢你,
S

【问题讨论】:

  • 这将取决于您如何表示 P,尽管字符列表似乎是唯一明智的选择。

标签: r compare dataframe


【解决方案1】:

不清楚原始数据来自哪里,所以我假设您将数据读入 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

然后我们可以使用applylength()intersect() 中的信息来获得您想要的。请注意,我还索引了 data.frame xrow.names() 属性,以获取您想要的行名称。

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] ,])))
      )

给你类似的东西:

  row1 row2 overlap
1   p1   p2       2
2   p1   p3       1
3   p2   p3       3

【讨论】:

    【解决方案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
    

    【讨论】:

    • 这是一个可扩展的解决方案,因为它适用于大文件。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-15
    • 1970-01-01
    • 2020-05-13
    • 1970-01-01
    相关资源
    最近更新 更多