oercim
oercim

Reputation: 1848

R-Subsetting a data frame conditional to related values

I have such a data frame(df):

col1  col2
a     2      
a     3 
b     7
b     5
c     4
c     2
c     1
d     5
d     7

Namely;

df<-data.frame(col1=c("a","a","b","b","c","c","c","d","d"), col2=c(2,3,7,5,4,2,1,5,7))

Desired output data frame(df1) is:

col1  col2
b     7
b     5
d     5
d     7

For example,

first row of df in col1 is 2. Related col1 value is "a". Then delete all rows which include "a" in col1. In the same way, 6th row of col2 is equal to 2. Related col1 value is equal to "c". Then delete all rows which include "c" in col1.

How can I do that using R? I will be very glad for any help. Thanks a lot.

Upvotes: 2

Views: 178

Answers (2)

cryo111
cryo111

Reputation: 4474

Base solution with subset.

subset(df,!col1%in%col1[col2==2])

Upvotes: 2

akrun
akrun

Reputation: 886938

You could try

library(data.table)
setDT(df)[, .SD[!col1 %in% col1[col2==2]]]
#    col1 col2
#1:    b    7
#2:    b    5
#3:    d    5
#4:    d    7

Or using dplyr

library(dplyr)
filter(df, !col1 %in% col1[col2==2])

Upvotes: 2

Related Questions