[英]Comparing rows of an R matrix with a predefined vector
我制作了一个值为 1 和 0 的矩阵,我想检查是否有一行或多行与 (0, 0, 0, 0, 0, 0, 0, 0, 0, 0) 相同。
我怎样才能做到这一点?
到目前为止,这是我制作矩阵的代码:
moeda <- c(0, 1)
n <- 100
casosTotais <- 0
casosFav <- 0
caras <- c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0) ## the vector to compare with
matriz <- matrix(nrow = n, ncol = 10)
i <- 1
lin <- 1
col <- 1
while(i <= n * 10){
matriz[lin, col] <- sample(moeda,1)
if(col==10){
lin <- lin + 1
col <- col - 10
}
i <- i + 1
col <- col + 1
}
matriz
我将首先假设一个带有 0 和 1 的一般caras
:
## a vector of TRUE/FALSE; TRUE means a row of `matriz` is identical to `caras`
comp <- colSums(abs(t(matriz) - caras)) == 0
那么如果caras
是一个简单的零向量:
## a vector of TRUE/FALSE; TRUE means a row of `matriz` only contains zeros
comp <- rowSums(matriz) == 0
如果要总结比较:
要知道caras
matriz
,请执行which(comp)
。
要知道caras
matriz
,请执行any(comp)
。
要知道有多少行matriz
与caras
相同,请执行sum(comp)
。
注意:您可以使用以下方法生成此随机矩阵:
## an n x 10 random matrix of zeros and ones
matriz <- matrix(rbinom(n * 10, size = 1, prob = 0.5), ncol = 10)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.