检查向量是否包含在R中的矩阵中

dmk*_*mkc 2 statistics r matrix

我无法相信这让我想起这么久,我仍然无法弄明白.

我需要保留一组向量,然后检查该集合中是否存在某个向量.我尝试了列表,%in%但似乎没有正常工作.

我的下一个想法是创建一个矩阵和rbind向量,但现在我不知道如何检查一个向量是否包含在矩阵中.%in似乎比较集合而不是精确行.相同似乎适用于交叉.

非常感谢!

Rei*_*son 9

你的意思是这样的:

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))
Run Code Online (Sandbox Code Playgroud)

我们可以用矩阵做类似的事情:

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))
Run Code Online (Sandbox Code Playgroud)

或按列:

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))
Run Code Online (Sandbox Code Playgroud)

如果您需要做很多事情,请编写自己的函数

vecMatch <- function(x, want) {
    isTRUE(all.equal(x, want))
}
Run Code Online (Sandbox Code Playgroud)

然后使用它,例如在列表中myList:

> sapply(myList, vecMatch, wantVec)
    A     B     C 
FALSE  TRUE FALSE 
> any(sapply(myList, vecMatch, wantVec))
[1] TRUE
Run Code Online (Sandbox Code Playgroud)

甚至包装整件事:

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
Run Code Online (Sandbox Code Playgroud)

编辑:快速评论为什么我使用isTRUE()缠绕all.equal()电话.这是因为两个参数相等的情况下,all.equal()不会返回逻辑值(FALSE):

> all.equal(1:3, c(3,2,1))
[1] "Mean relative difference: 1"
Run Code Online (Sandbox Code Playgroud)

isTRUE()在这里是有用的,因为它返回TRUEiff它的参数是TRUE,而FALSE如果它是其他任何东西它返回.