Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matrix %in% matrix

Tags:

r

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).

like image 709
Xu Wang Avatar asked Oct 30 '11 07:10

Xu Wang


People also ask

Can you have a matrix within a matrix?

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.

Who made The Matrix in The Matrix?

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.

What is a matrix to the power of a matrix?

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 .

Is there a second matrix?

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.


2 Answers

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
like image 156
Andrie Avatar answered Oct 23 '22 12:10

Andrie


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
like image 40
Patrick Burns Avatar answered Oct 23 '22 12:10

Patrick Burns