2011-12-02 109 views
2

我有两个数据帧AB,都是相同的尺寸。行和列标签不保证在帧之间按相同顺序排列。R中的数据帧行按位与或类似操作?

两个帧包含值01,与1指示指向“边缘”的帧的行和列(并且,相应地,0指示没有连接)之间存在。

我想找到两个框架通用的“边缘”。换句话说,我需要一个尺寸与AB相同的数据帧,其中包含1值,其中1位于AB的行和列中。

目前,我循环遍历行和列,并测试两者是否都是1

这有效,但我想有一个更有效的方式来做到这一点。有没有办法对数据帧的行向量执行“按位与”操作,这会返回一个行向量,我可以将其重新填充到新的数据框中?还是有另一种更智能(高效)的方法?

编辑

矩阵乘法是相当比我最初的方法更快。排序是完成这项工作的关键。

findCommonEdges <- function(edgesList) { 
    edgesCount <- length(edgesList) 
    print("finding common edges...") 
    for (edgesIdx in 1:edgesCount) { 
     print(paste("...searching against frame", edgesIdx, sep=" ")) 
     edges <- edgesList[[edgesIdx]] 
     if (edgesIdx == 1) { 
      # define commonEdges data frame as copy of first frame 
      commonEdges <- edges 
      next 
     } 
     # 
     # we reorder edge data frame row and column labels 
     # to do matrix multiplication and find common edges 
     # 
     edges <- edges[order(rownames(commonEdges)), order(colnames(commonEdges))] 
     commonEdges <- commonEdges * edges 
    } 
    commonEdges 
} 

回答

3

你可以使用正常的乘法! :-)

// generate data 
a = matrix(rbinom(100, 1, 0.5), nrow = 10) 
b = matrix(rbinom(100, 1, 0.5), nrow = 10) 

a * b // this is the result! 

你也可以使用逻辑运算符&,这是“按位与”你所期待的。你的表情看起来像(a & b) + 0+ 0将只从布尔转换回整数)。

注意:数据框的工作原理完全相同。

+0

是的,这样比较好。 :) – joran

+0

谢谢,@joran :-)这个例子显示R是非常优雅的语言,我喜欢享受它的优雅:-) – TMS

+0

谢谢,这是非常有道理的,我只需要以相同的方式排序两个帧,所以结果是正确的。 –

0

可能是这样的吗?

df1 <- as.data.frame(matrix(sample(0:1,25,replace = TRUE),5,5)) 
df2 <- as.data.frame(matrix(sample(0:1,25,replace = TRUE),5,5)) 
df3 <- matrix(0,5,5) 
df3[df1 == 1 & df2 == 1] <- 1 
> df3 
    [,1] [,2] [,3] [,4] [,5] 
[1,] 0 0 0 0 0 
[2,] 0 0 0 1 1 
[3,] 1 1 1 0 0 
[4,] 0 1 0 0 0 
[5,] 0 0 0 0 0 

我已经结束了一个矩阵,但如果需要的话,您可以再次将它转换回数据框。但是如果你只是处理0/1数据,没有真正的理由不使用矩阵。 (然后,我不知道你的具体情况的很多细节...)