Suppose I have two matrices, each with two columns and differing numbers of row. I want to check and see which pairs of one matrix are in the other matrix. If these were one-dimensional, I would normally just do a %in% x
to get my results. match
seems only to work on vectors.
> a
[,1] [,2]
[1,] 1 2
[2,] 4 9
[3,] 1 6
[4,] 7 7
> x
[,1] [,2]
[1,] 1 6
[2,] 2 7
[3,] 3 8
[4,] 4 9
[5,] 5 10
I would like the result to be c(FALSE,TRUE,TRUE,FALSE)
.
You can certainly do so if all the elements of your matrix lie in some common structure (X,+,⋅), i.e., a set endowed with addition and multiplication operations.
The Wachowskis, Lana Wachowski (born June 21, 1965) and Lilly Wachowski (born December 29, 1967), are American film directors, writers and producers, most famous for creating The Matrix franchise including writing and directing the Matrix trilogy.
The power of a matrix for a nonnegative integer is defined as the matrix product of copies of , A matrix to the zeroth power is defined to be the identity matrix of the same dimensions, . The matrix inverse is commonly denoted , which should not be interpreted to mean .
The Matrix Reloaded is a 2003 American science-fiction action film written and directed by the Wachowskis. It is a sequel to The Matrix (1999) and the second installment in the Matrix film series.
Recreate your data:
a <- matrix(c(1, 2, 4, 9, 1, 6, 7, 7), ncol=2, byrow=TRUE)
x <- matrix(c(1, 6, 2, 7, 3, 8, 4, 9, 5, 10), ncol=2, byrow=TRUE)
Define a function %inm%
that is a matrix analogue to %in%
:
`%inm%` <- function(x, matrix){
test <- apply(matrix, 1, `==`, x)
any(apply(test, 2, all))
}
Apply this to your data:
apply(a, 1, `%inm%`, x)
[1] FALSE TRUE TRUE FALSE
To compare a single row:
a[1, ] %inm% x
[1] FALSE
a[2, ] %inm% x
[1] TRUE
Another approach would be:
> paste(a[,1], a[,2], sep="$$") %in% paste(x[,1], x[,2], sep="$$")
[1] FALSE TRUE TRUE FALSE
A more general version of this is:
> apply(a, 1, paste, collapse="$$") %in% apply(x, 1, paste, collapse="$$")
[1] FALSE TRUE TRUE FALSE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With