[英]R: finding rows of one matrix in another matrix
我們從:
m1 = matrix(c(1:32), ncol=4, byrow = T); m2 = matrix(c(1:16), ncol=4, byrow=T);
如果不明顯,這將產生2個矩陣,一個是8x4,另一個是4x4,使得前者的前4行與后者的前4行相同。
我想要一個帶sudo / semi代碼的函數;
#x is always the bigger; an if check can be put here but assume nrow(x) > nrow(y)
countAinB<-function(x, y){
#new matrix of 0s that has the same dim of x, add 1 extra column for adding found/not found (0/1) coding
c <-matrix(0, ncol(x)+1, nrow(x))
#need change of for, it is slow in R
for (i in 1:nrow(y)){
#bad R below
if(y[i,] in x){
??add a 1 to the column matching the found row of y in x to c
}}
return(c)
}
C <- countAinB(M1,M2)
現在C,是一個與X相同的矩陣,除了它有一個0和1的列,表示在M1中找到了M2。
我的真實數據集很大,所以試圖找到最佳解決方案。
data.table
是解決此類問題的快速解決方案:
library(data.table)
DT1 <- data.table(m1)
DT2 <- data.table(cbind(m2, 0), key=paste0("V", seq(len=ncol(m2))))
setnames(DT2, c(head(names(DT2), -1L), "found"))
DT2[DT1, list(found=ifelse(is.na(found), 0, 1))]
在這里,我們使用每個的前四列將DT2
LETER DT2
到DT1
。 這會產生:
# V1 V2 V3 V4 found
# 1: 1 2 3 4 1
# 2: 5 6 7 8 1
# 3: 9 10 11 12 1
# 4: 13 14 15 16 1
# 5: 17 18 19 20 0
# 6: 21 22 23 24 0
# 7: 25 26 27 28 0
# 8: 29 30 31 32 0
found
表示兩個對象中是否存在該行。 您可以使用as.matrix
轉換回矩陣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.