Comparing rows of an R matrix with a predefined vector

Viewed 42

I have made a matrix with values 1 and 0, and I want to check if there is one or more rows identical to (0, 0, 0, 0, 0, 0, 0, 0, 0, 0).

How can I do this?

Here's my code so far for making the matrix:

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
1 Answers

I will first assume a general caras with zeros and ones:

## a vector of TRUE/FALSE; TRUE means a row of `matriz` is identical to `caras`
comp <- colSums(abs(t(matriz) - caras)) == 0

Then if caras is a simply a vector of zeros:

## a vector of TRUE/FALSE; TRUE means a row of `matriz` only contains zeros
comp <- rowSums(matriz) == 0

If you want to summarize the comparison:

  • To know which rows of matriz are identical to caras, do which(comp).

  • To know if any row of matriz is identical to caras, do any(comp).

  • To know how many rows of matriz is identical to caras, do sum(comp).


Note: You can generate this random matrix using:

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