r - 将 R 矩阵的行与预定义向量进行比较

标签 r matrix 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

最佳答案

我首先假设一个带有零和一的通用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

如果您想总结比较:

  • 要了解 matriz 的哪些行与 caras 相同,请执行 which(comp)

  • 要知道 matriz 的任何行是否与 caras 相同,请执行 any(comp)

  • 要知道有多少行 matrizcaras 相同,请执行 sum(comp)


注意:您可以使用以下方法生成此随机矩阵:

## an n x 10 random matrix of zeros and ones
matriz <- matrix(rbinom(n * 10, size = 1, prob = 0.5), ncol = 10)

关于r - 将 R 矩阵的行与预定义向量进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73045498/

相关文章:

r - 为什么 write.xlsx2 不存储不同的电子表格?

r - HTTR 获取新错误 : SSL certificate problem: certificate has expired

如果向量的任何值在列表中,则返回 true

r - tm 包 : Output of findAssocs() in a matrix instead of a list in R

vector - 关于 Julia 中向量的行为/向量的行为

c++ - 使用 STL/Boost 查找和修改 vector 中的匹配元素

r - 将函数参数传递给 dplyr 和 ggplot

CUDA 矩阵乘法写入错误的内存位置

python - 如何在Python中构造对称矩阵

C++ vector 运算符重载