How to verify the presence of each element of a vector, line by line in a matrix in R?

Asked

Viewed 44 times

3

Suppose I have a vector that goes from 1 to 10. I want to check binary for each element of the vector if it is present in the matrix line, being 0 for no presence and 1 for presence, regardless of the element repeat I would only count 1 for it.

For example, in the first row of the matrix I have a[1,]= c(1,5,2,2,1). Thus, I would have 0 for the elements 3,4,6,7,8,9,10 and 1 for the elements 1,2,5.

1 answer

5

The function %in% does exactly what is sought. Be the matrix a given by

a <- matrix(c(1, 5, 2, 2, 1, 
              2, 3, 4, 1, 1, 
              3, 8, 9, 6, 7), nrow = 3, byrow = TRUE)

And be the vector v with elements 1 to 10:

v <- 1:10

See what we get by running the code below:

v %in% a[1, ]
## [1]  TRUE  TRUE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE

To convert TRUE and FALSE in 0 and 1, use the function as.numeric:

as.numeric(v %in% a[1, ])
## [1] 1 1 0 0 1 0 0 0 0 0

To apply this result to all rows of the matrix, use the function apply, with the parameter 1, indicating that calculations will be made by lines:

t(apply(a, 1, function(x) as.numeric(v %in% x)))
##      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
## [1,]    1    1    0    0    1    0    0    0    0     0
## [2,]    1    1    1    1    0    0    0    0    0     0
## [3,]    0    0    1    0    0    1    1    1    1     0

Browser other questions tagged

You are not signed in. Login or sign up in order to post.