Comparison of two matrices with different sizes

Asked

Viewed 122 times

5

I have two matrices with these dimensions and would like to remove the common lines between the two matrices and form another matrix without these elements. How R could do that?

a = matrix(1:30, ncol = 5, byrow = T)

b = matrix(6:15, ncol = 5, byrow = T)

1 answer

5


Some ways to be doing that (I still think there’s some smarter):

a[!apply(a, 1, function(arow) any(apply(b, 1, function(brow) all(brow==arow)))),]

In this case, each row of the matrix a will be compared with each row of the matrix b, and if there is any line of a with all elements equal to a line of b, the row is excluded.

Another way is to join the two matrices and use duplicated():

ab <- rbind(a, b)
ab[!(duplicated(ab, fromLast = TRUE) | duplicated(ab)),]

In this case the lines of ab duplicates are removed, leaving only single lines. It is necessary to use duplicated twice because the function only returns TRUE for the second occurrence of the line, so we search once from top to bottom and one from bottom to top, removing all duplicate lines.

The two methods return:

     [,1] [,2] [,3] [,4] [,5]
[1,]    1    2    3    4    5
[2,]   16   17   18   19   20
[3,]   21   22   23   24   25
[4,]   26   27   28   29   30

Browser other questions tagged

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