Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Output should be

FALSE  FALSE FALSE FALSE TRUE
like image 548
wolfsatthedoor Avatar asked Sep 17 '15 22:09

wolfsatthedoor


People also ask

How do you check if all values in row is equal in R?

To check for equality of three columns by row, we can use logical comparison of equality with double equal sign (==) and & operator.

How do you know if something is a vector in R?

To check if given object is a vector in R, call is. vector() function and pass the given object as argument to it. If the given object x is of type vector, then is. vector(x) returns TRUE , else it returns FALSE .

Is a matrix a vector in R?

A vector can be created by using c() function. Vectors in R are the same as the arrays in C language which are used to hold multiple data values of the same type. Vectors can also be used to create matrices. Matrices can be created with the help of Vectors by using pre-defined functions in R Programming Language.

How do you show rows of a matrix in R?

R – Get Specific Row of Matrix To get a specific row of a matrix, specify the row number followed by a comma, in square brackets, after the matrix variable name. This expression returns the required row as a vector.


1 Answers

One possibility is

rowSums(M == v[col(M)]) == ncol(M)
## [1] FALSE FALSE FALSE FALSE  TRUE

Or simlarly

rowSums(M == rep(v, each = nrow(M))) == ncol(M)
## [1] FALSE FALSE FALSE FALSE  TRUE

Or

colSums(t(M) == v) == ncol(M)
## [1] FALSE FALSE FALSE FALSE  TRUE

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)

like image 138
David Arenburg Avatar answered Sep 20 '22 13:09

David Arenburg