How to use lapply functions for logical operations across columns in a matrix in R?

Is there a way to use apply in a matrix to compare items across columns with logical operators?

n.col <- 2
A <- matrix(sample(1:6, 1000*n.col, replace = TRUE), 1000 , ncol=n.col)

For each row I would like to check if the values of across cols are the same. For small values of n.col I just do:

A[ ,1] == A[ ,2]

But this gets pretty unwieldy for large n.cols. I could do something ugly with a loop but I would love to know if there is some way to use apply/lapply for this.

Upvotes: 2

Views: 3222

Answers (1)

maccruiskeen
maccruiskeen

Reputation: 2808

You can use apply for rows/columns of a matrix:

cols.equal <- apply(A, 1, function(x) length(unique(x)) == 1)

Edit: If your application involves floating point numbers, length(unique(x)) won't really work because numbers will be "almost" the same, yet the number of unique elements will be larger than one. If that's the case, you can replace the function inside apply with the answer here: Test for equality among all elements of a single vector

Upvotes: 3

Related Questions