2010-11-27 38 views
1

我不敢相信這會花費我很長時間才能弄清楚,但我仍然無法弄清楚。檢查一個向量是否包含在R中的矩陣中

我需要保留一組向量,然後檢查某個向量是否在該集合中。我嘗試了與%in%結合的列表,但似乎無法正常工作。我的下一個想法是創建一個矩陣和rbind向量,但現在我不知道如何檢查一個向量是否包含在矩陣中。似乎是比較集合而不是確切的行。似乎適用於相交。

非常感謝!

+0

,什麼是編程語言,請相交()? – kellogs 2010-11-27 22:13:51

回答

7

你的意思是這樣的:

wantVec <- c(3,1,2) 
myList <- list(A = c(1:3), B = c(3,1,2), C = c(2,3,1)) 
sapply(myList, function(x, want) isTRUE(all.equal(x, want)), wantVec) 
## or, is the vector in the set? 
any(sapply(myList, function(x, want) isTRUE(all.equal(x, want)), wantVec)) 

我們可以做類似的事情用一個矩陣:

myMat <- matrix(unlist(myList), ncol = 3, byrow = TRUE) 
## As the vectors are now in the rows, we use apply over the rows 
apply(myMat, 1, function(x, want) isTRUE(all.equal(x, want)), wantVec) 
## or 
any(apply(myMat, 1, function(x, want) isTRUE(all.equal(x, want)), wantVec)) 

還是列:如果您需要做的

myMat2 <- matrix(unlist(myList), ncol = 3) 
## As the vectors are now in the cols, we use apply over the cols 
apply(myMat, 2, function(x, want) isTRUE(all.equal(x, want)), wantVec) 
## or 
any(apply(myMat, 2, function(x, want) isTRUE(all.equal(x, want)), wantVec)) 

這很多,寫你自己的功能

vecMatch <- function(x, want) { 
    isTRUE(all.equal(x, want)) 
} 

然後使用它,例如,

> sapply(myList, vecMatch, wantVec) 
    A  B  C 
FALSE TRUE FALSE 
> any(sapply(myList, vecMatch, wantVec)) 
[1] TRUE 

甚至包裹住整個事情:名單上myList

vecMatch <- function(x, want) { 
    out <- sapply(x, function(x, want) isTRUE(all.equal(x, want)), want) 
    any(out) 
} 

> vecMatch(myList, wantVec) 
[1] TRUE 
> vecMatch(myList, 5:3) 
[1] FALSE 

編輯:爲什麼我用isTRUE()圍繞all.equal()電話裹快速評論。這是由於這樣的事實,當兩個參數是相等,all.equal()不返回邏輯值(FALSE):

> all.equal(1:3, c(3,2,1)) 
[1] "Mean relative difference: 1" 

isTRUE(),因爲它返回TRUE當且僅當它的參數是TRUE在這裏有用,如果它是其他東西,它將返回FALSE

0
> M 
    [,1] [,2] [,3] 
[1,] 1 4 7 
[2,] 2 5 8 
[3,] 3 6 9 


v <- c(2, 5, 8) 

檢查每一列:

c1 <- which(M[, 1] == v[1]) 
c2 <- which(M[, 2] == v[2]) 
c3 <- which(M[, 3] == v[3]) 

這是一種方法,仍然使用上超過2個元素

> intersect(intersect(c1, c2), c3) 

[1] 2 
相關問題