检查矩阵行是否等于R中的向量 [英] check whether matrix rows equal a vector in R , vectorized
问题描述
我很惊讶没有提出这个问题,也许答案会弄清楚为什么.我想将矩阵的行与向量进行比较,并返回是否行==向量到处都是.请参见下面的示例.我想要一个矢量化的解决方案,没有任何应用函数,因为矩阵太大,无法进行慢速循环.假设还有很多行,所以我要避免重复向量.
I'm very surprised this question has not been asked, maybe the answer will clear up why. I want to compare rows of a matrix to a vector and return whether the row == the vector everywhere. See the example below. I want a vectorized solution, no apply functions because the matrix is too large for slow looping. Suppose there are many rows as well, so I would like to avoid repping the vector.
set.seed(1)
M = matrix(rpois(50,5),5,10)
v = c(3 , 2 , 7 , 7 , 4 , 4 , 7 , 4 , 5, 6)
M
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 4 8 3 5 9 4 5 6 7 7
[2,] 4 9 3 6 3 1 5 7 6 1
[3,] 5 6 6 11 6 4 5 2 7 5
[4,] 8 6 4 4 3 8 3 6 5 6
[5,] 3 2 7 7 4 4 7 4 5 6
输出应为
FALSE FALSE FALSE FALSE TRUE
推荐答案
一种可能性是
rowSums(M == v[col(M)]) == ncol(M)
## [1] FALSE FALSE FALSE FALSE TRUE
或者类似地
rowSums(M == rep(v, each = nrow(M))) == ncol(M)
## [1] FALSE FALSE FALSE FALSE TRUE
或
colSums(t(M) == v) == ncol(M)
## [1] FALSE FALSE FALSE FALSE TRUE
v[col(M)]
是rep(v, each = nrow(M))
的较短版本,它创建一个与M
大小相同的向量(矩阵只是一个向量,请尝试c(M)
),然后使用==
是具有array
方法的通用函数(请参见methods("Ops")
和is.array(M)
),该方法允许我们在其上运行rowSums
(或colSums
)以确保我们有足够的数量匹配为ncol(M)
v[col(M)]
is just a shorter version of rep(v, each = nrow(M))
which creates a vector the same size as M
(matrix is just a vector, try c(M)
) and then compares each element against its corresponding one using ==
. Fortunately ==
is a generic function which has an array
method (see methods("Ops")
and is.array(M)
) which allows us to run rowSums
(or colSums
) on it in order to makes sure we have the amount of matches as ncol(M)
这篇关于检查矩阵行是否等于R中的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!