# Filter Rows Based on Conditions in a DataFrame in R

Last Updated : 27 Mar, 2024

In this article, we will explore various methods to filter rows based on Conditions in a data frame by using the R Programming Language.

## How to filter rows based on Conditions in a data frame

R language offers various methods to filter rows based on Conditions in a data frame. By using these methods provided by R, it is possible to filter rows. Some of the methods to filter rows based on conditions are:

### Filter rows based on a single condition

This method is used to filter rows based on a single condition. In the below example, we created a data frame and filtered rows based on a single condition.

R ```df <- data.frame( name=c("a","b","c","d","e","f"), id=c(100,250,300,450,500,600), age=c(10,20,30,35,40,50) ) print(df) res <- df[df\$id > 400, ] print("The resultant data frame is") print(res) ```

Output:

`  name  id age1    a 100  102    b 250  203    c 300  304    d 450  355    e 500  406    f 600  50[1] "The resultant data frame is"  name  id age4    d 450  355    e 500  406    f 600  50`

In the below example, we created a data frame and filtered rows based on a single condition.

R ```df <- data.frame( name=c("a","b","c","d","e","f"), id=c(100,250,300,450,500,600), age=c(10,20,30,35,40,50) ) print(df) res <- df[df\$age > 35, ] print("The resultant data frame is") print(res) ```

Output:

`  name  id age1    a 100  102    b 250  203    c 300  304    d 450  355    e 500  406    f 600  50[1] "The resultant data frame is"  name  id age5    e 500  406    f 600  50`

### Filter rows based on Multiple conditions

These method is used to filter the rows based on multiple conditions. In the below example, we created a data frame and filtered rows based on multiple conditions.

R ```df <- data.frame( name=c("a","b","c","d","e","f"), id=c(100,250,300,450,500,600), age=c(10,20,30,35,40,50) ) print(df) res <- df[df\$age > 30 & df\$id == 450, ] print("The resultant data frame is") print(res) ```

Output:

`   name id age1    a     100  102    b    250  203    c    300  304    d   450  355    e    500  406    f     600  50[1] "The resultant data frame is"  name  id age4    d 450  35`

In the below example, we created a data frame and filtered rows based on multiple conditions.

R ```df <- data.frame( name=c("a","b","c","d","e","f"), id=c(100,250,300,450,500,600), age=c(10,20,30,35,40,50) ) print(df) res <- df[df\$name %in% c("b", "e"), ] print("The resultant data frame is") print(res) ```

Output:

`   name  id  age1    a      100  102    b    250  203    c    300  304    d    450  355    e    500  406    f     600  50[1] "The resultant data frame is"  name  id age2    b 250  205    e 500  40`

### Conclusion

In conclusion, we learned about how to filter rows based on conditions in a data frame. R programming language offers versatile tools while handling to filter rows based on conditions in a data frame.