0

I have a matrix A:

> A
      [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6
[3,]    7    8    9
[4,]    1    2    3
[5,]    4    5    6
[6,]    7    8    9

and a matrix B:

> B
      [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6

I want to delete the rows in matrix A, which appear in B. And the result should be:

> C
      [,1] [,2] [,3]    
[1,]    7    8    9
[2,]    7    8    9

Thanks a lot!

Ghrua
  • 6,746
  • 5
  • 17
  • 25
  • This should help: http://stackoverflow.com/questions/10907359/r-remove-rows-from-one-data-frame-that-are-in-another – Gaurav Taneja Apr 13 '16 at 11:17
  • You could do sometype of an anti-join- see [here](http://stackoverflow.com/questions/28702960/find-complement-of-a-data-frame-anti-join). Using `data.table`, this could be `library(data.table);DTA <- data.table(A);DTB <- data.table(B);DTA[!DTB, on = names(DTA)]` – David Arenburg Apr 13 '16 at 11:31
  • @GauravTaneja it works and it's a little tricky, thanks a lot – Ghrua Apr 13 '16 at 11:39
  • @HuaYoung it actually doesn't work for your example. Simply because you have two duplicated rows in your first matrix which doesn't appear in your second matrix and hence also got removed. – David Arenburg Apr 13 '16 at 11:46
  • @DavidArenburg you are right, I think I should update my problem. Actually I don't care the duplicated rows. Thank you! – Ghrua Apr 13 '16 at 12:13
  • @DavidArenburg I am sorry that I cannot update the example, because some people have answered me. The rows of the real data that I am using are unique. – Ghrua Apr 13 '16 at 12:36

3 Answers3

2

We can use anti_join

library(dplyr)
as.matrix(anti_join(as.data.frame(A), as.data.frame(B)))
#     V1 V2 V3
#[1,]  7  8  9
#[2,]  7  8  9
akrun
  • 874,273
  • 37
  • 540
  • 662
1

First create the above two matricies

A <- matrix(rep(c(1:9),2),ncol=3,byrow = T)
B <- matrix(1:6,ncol=3,byrow = T)

Get the index of rows to be removed

Indx <- apply(B,1,function(x) apply(A,1,function(y) all.equal(x,y)))
Indx <- apply(Indx,1,any)

Remove the rows from first matrix

A[-which(Indx),]
Koundy
  • 5,265
  • 3
  • 24
  • 37
0

Make use of match_df function inside plyr package.

    library(plyr)
    A = matrix(rep(1:9,2),nrow=6,byrow=T)
    B = matrix(1:6,nrow=2,byrow=T)

    M_ROWS = as.numeric(rownames(match_df(data.frame(A),data.frame(B))))
    # Matching on: X1, X2, X3

    Result <- A[-M_ROWS,]
    Result
    #      [,1] [,2] [,3]
    # [1,]    7    8    9
    # [2,]    7    8    9
Sowmya S. Manian
  • 3,723
  • 3
  • 18
  • 30