New2coding
New2coding

Reputation: 717

How to compare each line of matrix with elements of vector in R

I would like to compare each line of given matrix with all elements of given vector:

matrix <- matrix(c(c("var1","var2"),c("var4","var5"),c("var6","var7")),nrow = 3, ncol = 2)
vector <- c("var1", "var2", "var3", "var4", "var5", "var6")

The desired outcome would be just: TRUE because the elements of first line of matrix are contained within given vector.

If the matrix was defined as:

matrix <- matrix(c(c("var6","var7"),c("var1","var8"),c("var2","var9")),nrow = 3, ncol = 2)

The the desired outcome would be in this case FALSE because the elements of all rows of matrix are not contained within given vector. Any suggestions? Thanks!

Upvotes: 0

Views: 910

Answers (1)

MrFlick
MrFlick

Reputation: 206401

Sounds like you just need apply here

apply(matrix, 1, function(x) all(x %in% vector))

This looks across all the rows of the matrix to see if all values in a given row are in the vector.

Upvotes: 1

Related Questions