Comparison of two matrices with different sizes

5

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

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

b = matrix(6:15, ncol = 5, byrow = T)
    
asked by anonymous 31.05.2015 / 21:40

1 answer

5

Some ways of doing this (I still think there are some smarter ones):

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

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

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

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

In this case, duplicate ab rows are removed, leaving only single rows remaining. 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
    
31.05.2015 / 22:49