Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: Filtering by two columns using "is not equal" operator dplyr/subset

Tags:

r

dplyr

This questions must have been answered before but I cannot find it any where. I need to filter/subset a dataframe using values in two columns to remove them. In the examples I want to keep all the rows that are not equal (!=) to both replicate "1" and treatment "a". However, either subset and filter functions remove all replicate 1 and all treatment a. I could solve it by using which and then indexing, but it is not the best way for using pipe operator. do you know why filter/subset do not filter only when both conditions are true?

require(dplyr)

#Create example dataframe
replicate = rep(c(1:3), times = 4)
treatment = rep(c("a","b"), each = 6)

df = data.frame(replicate, treatment)

#filtering data    
> filter(df, replicate!=1, treatment!="a")
  replicate treatment
1         2         b
2         3         b
3         2         b
4         3         b
> subset(df, (replicate!=1 & treatment!="a"))
   replicate treatment
8          2         b
9          3         b
11         2         b
12         3         b

#solution by which - indexing
index = which(df$replicate==1 & df$treatment=="a")
> df[-index,]
   replicate treatment
2          2         a
3          3         a
5          2         a
6          3         a
7          1         b
8          2         b
9          3         b
10         1         b
11         2         b
12         3         b
like image 829
Mirko Pavicic Avatar asked Jan 04 '23 05:01

Mirko Pavicic


1 Answers

I think you're looking to use an "or" condition here. How does this look:

require(dplyr)

#Create example dataframe
replicate = rep(c(1:3), times = 4)
treatment = rep(c("a","b"), each = 6)

df = data.frame(replicate, treatment)
df %>% 
  filter(replicate != 1 | treatment != "a")

   replicate treatment
1          2         a
2          3         a
3          2         a
4          3         a
5          1         b
6          2         b
7          3         b
8          1         b
9          2         b
10         3         b
like image 96
cody_stinson Avatar answered Jan 14 '23 02:01

cody_stinson