我有兩個數據幀A
和B
,都是相同的尺寸。行和列標籤不保證在幀之間按相同順序排列。R中的數據幀行按位與或類似操作?
兩個幀包含值0
和1
,與1
指示指向「邊緣」的幀的行和列(並且,相應地,0
指示沒有連接)之間存在。
我想找到兩個框架通用的「邊緣」。換句話說,我需要一個尺寸與A
和B
相同的數據幀,其中包含1
值,其中1
位於A
和B
的行和列中。
目前,我循環遍歷行和列,並測試兩者是否都是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
}
是的,這樣比較好。 :) – joran
謝謝,@joran :-)這個例子顯示R是非常優雅的語言,我喜歡享受它的優雅:-) – TMS
謝謝,這是非常有道理的,我只需要以相同的方式排序兩個幀,所以結果是正確的。 –