How to filter a frame with multiple conditions?

I have this framework that I would like to multiply (if possible, with functions dplyror base R):

df <- data.frame(x = c(1,1,1,2,2,2), y = c(30,10,8,10,18,5))

x  y
1 30
1 10
1  8
2 10
2 18
2  5

Assuming x are factors (so there are 2 conditions / levels), how can I multiply / filter this data frame to get only values df$ythat are more than 15 for df$x == 1and df$yvalues ​​that are more than 5 for df$x == 2?

This is what I would like to receive:

df2 <- data.frame(x = c(1,2,2), y = c(30,10,18))

x y
1 30
2 10
2 18

Appreciate any help! Thank!

+4
source share
2 answers

you can try this

with(df, df[ (x==1 & y>15) | (x==2 & y>5), ])
  x  y
1 1 30
4 2 10
5 2 18

or with dplyr

library(dplyr)
filter(df, (x==1 & y>15) | (x==2 & y>5))
+2
source

"x", mapply. split "y", "x" , (c(15,5)) mapply 'df'.

df[unlist(mapply('>', split(df$y, df$x), c(15,5))),]
#  x  y
#1 1 30
#4 2 10
#5 2 18
+2

All Articles