2010-11-27 37 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 
相关问题