4

I would like to remove rows that have specific values for columns that match values in another data frame.

a<-c(1,1,2,2,2,4,5,5,5,5)
b<-c(10,10,22,30,30,30,40,40,40,40)
c<-c(1,2,1,2,2,2,2,1,1,2)
d<-rnorm(1:10)
data<-data.frame(a,b,c,d)

a<-c(2,5)
b<-c(30,40)
c<-c(2,1)
x<-data.frame(a,b,c)

So that y can become:

 a  b c          d
 1 10 1 -0.2509255
 1 10 2  0.4142277
 2 22 1 -0.1340514
 4 30 2 -1.5372009
 5 40 2  1.9001932
 5 40 2 -1.2825212

I tried the following, which did not work:

y<-data[!data$a==a & !data$b==b & !data$c==c,] 

y<-subset(data, !data$a==x$a & !data$b==x$b & !data$c==x$c)

I also tried to just flag the ones that should be removed in order to subset in a second step, but this did not work either:

y<-data
y$rm<-ifelse(y$a==x$a & y$b==x$b & y$c==x$c, 1, 0)

The real "data" and "x" are much longer, and there are variable number of rows in data that match each row in x.

Maya
  • 55
  • 1
  • 6

1 Answers1

5

We can use anti_join from dplyr. It will return all rows from 'data' that are not matching values in 'x'. We specify the variables to be considered in the by argument.

library(dplyr)
anti_join(data, x, by=c('a', 'b', 'c'))
akrun
  • 874,273
  • 37
  • 540
  • 662