Nazer
Nazer

Reputation: 3764

Filter data in R based on two conditions?

I am trying to exclude some data from R based on two conditions -- treatment and depth. I want to get rid of data that is in the P and PF trt, but only at 5 cm depth. I have tried

df<-df[df$trt != "P" & df$depth != "5",]

but this gets rid of everything in the P treatment and everything at 5 cm depth. I was just planning to do it again to get rid of the other trt PF.

df<-df[df$trt != "PF" & df$depth != "5",]

What do I use to specify that the exclusions need to happen together?

Here is an example of my data:

trt depth mass
P    5    3
P    15   4
P    30   2
P    45   3
PF   5    2
PF   15   5
PF   30   2
CC   5    2
CC   15   3
CW   5    2
CW   15   4
CL   5    4
CL   30   2

Upvotes: 0

Views: 108

Answers (1)

Blue Magister
Blue Magister

Reputation: 13363

This is a logic error, not an R error. If you want to get rid of data where both conditions hold, you want

df<-df[!(df$trt %in% c("P","PF") & df$depth == "5"),]

equivalently,

df<-df[!(df$trt %in% c("P","PF") | df$depth != "5"),]

Upvotes: 2

Related Questions