Filtering R data-frame with multiple conditions

753    Asked by debbieJha in SQL Server , Asked on Jul 27, 2021
a  b
1 30
1 10
1  8
2 10
2 18
2  5

I have this data-set with me, where column 'a' is of factor type with levels '1' and '2'. Column 'b' has random whole numbers. Now, i would want to filter this data-frame such that i only get values more than 15 from 'b' column where 'a=1' and get values greater 5 from 'b' where 'a==2'

So, i would want the output to be like this:

a b
1 30
2 10
2 18

How  R filter data frame multiple conditions?

Answered by Anurag Singhal

The filter() function is used to filter data frame multiple conditions and produce a subset of the data frame, retaining all rows that satisfy the specified conditions. The filter() method in R can be applied to both grouped and ungrouped data.

 You can use the 'filter' function from 'dplyr' package to solve this:

filter(df, (a==1 & b>15) | (a==2 & b>5))

Your Answer


Parent Categories