2011-12-02 38 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數據,沒有真正的理由不使用矩陣。 (然後,我不知道你的具體情況的很多細節...)