filter() Method in R (original) (raw)

Last Updated : 21 Jul, 2025

The filter method in R is used to select specific rows from a data frame that meet certain conditions. It helps us work with only the data we need, making analysis easier and faster. We use it when we want to find rows that match some rules or values.

**Syntax:

filter(data_frame, condition)

**Parameters:

Implementation of filter Method

Then we follow these steps to apply the filter method in R.

1. Install then load the dplyr package

We first install and then load the dplyr package to use the filter method.

install.packages("dplyr") library(dplyr)

`

2. Creating a sample dataset

We create a simple data frame of employees using basic R functions.

employees <- data.frame( ID = 1:10, Name = c("John", "Jane", "Bill", "Anna", "Tom", "Sue", "Mike", "Sara", "Alex", "Nina"), Department = c("HR", "Finance", "IT", "Finance", "IT", "HR", "IT", "Finance", "HR", "Finance"), Salary = c(50000, 60000, 70000, 65000, 72000, 48000, 75000, 67000, 52000, 69000) )

print(employees)

`

**Output:

department

Output

3. Filtering rows with one condition

We filter employees whose department is IT.

it <- filter(employees, Department == "IT") print(it)

`

**Output:

department

Department

4. Filtering rows with multiple conditions

We filter employees from Finance who have a salary more than 65000.

high_paid_finance_employees <- filter(employees, Department == "Finance" & Salary > 65000) print(high_paid_finance_employees)

`

**Output:

department

Output

5. Filtering with or and in

We filter employees who are in either HR or IT andalso use %in% for filtering multiple values.

hr_it_employees <- employees %>% filter(Department == "HR" | Department == "IT") print(hr_it_employees)

hr_finance_employees <- employees %>% filter(Department %in% c("HR", "Finance")) print(hr_finance_employees)

`

**Output:

deapartment

Output

This method helps us quickly find the rows we need and makes our data easier to work with in R.