01 / 20

The filter() Function
in R

Learn how to select specific rows from a data frame using logical conditions with the powerful dplyr filter() function.

R Programming

What is filter()?

filter() is a function from the dplyr package in R. It lets you extract rows from a data frame that satisfy one or more logical conditions. Think of it as asking your data a yes/no question: only the rows that answer "yes" are kept.

How filter() Works Visually

Original Data name score Ali 95 Ben 72 Cara 91 Dana 68 Eli 98 Fay 85
\( \text{filter(score > 90)} \)
Filtered Result name score Ali 95 Cara 91 Eli 98 Only 3 of 6 rows remain

Why filter() Matters

★ Real-World Data is Big
Datasets often have thousands or millions of rows. You need to zoom in on relevant subsets to answer specific questions.
★ Foundation for Analysis
Filtering is the first step in almost every data analysis workflow: clean, subset, then summarize or visualize.
★ Readable Code
dplyr's filter() uses clear, human-readable syntax that is far easier to understand than base R bracket subsetting.

The Core Syntax

filter(.data, condition1, condition2, ...)
.data
The data frame (or tibble) you want to filter.
conditions
Logical expressions. Rows where all conditions evaluate to TRUE are kept.

Logical Operators in Conditions

Operator Meaning Example
\( == \) Equal to \( \text{grade} == \text{"A"} \)
\( != \) Not equal to \( \text{city} != \text{"NYC"} \)
\( > \) , \( \ge \) Greater than (or equal) \( \text{score} > 90 \)
\( < \) , \( \le \) Less than (or equal) \( \text{age} \le 18 \)
\( \& \) AND \( \text{score} > 80 \& \text{grade} == \text{"B"} \)
\( | \) OR \( \text{city} == \text{"LA"} | \text{city} == \text{"SF"} \)
\( \%in\% \) Is in a set \( \text{color} \%in\% \text{c("red","blue")} \)

filter() vs. Base R Subsetting

dplyr filter()
filter(students, score > 90)
Base R brackets
students[students$score > 90, ]

How to Apply filter()

1
Load dplyr. Use library(dplyr) or library(tidyverse) at the top of your script.
2
Identify the data frame. Know the name of your data frame and the columns you want to test.
3
Write your condition(s). Use column names directly (no \( \$ \) needed). Combine multiple conditions with commas (AND) or \( | \) (OR).
4
Run and verify. Check the output dimensions and values to confirm your filter behaves as expected.
5
Store or pipe. Assign the result to a new variable, or pipe it into further operations like select(), mutate(), or summarize().

Example 1: Single Condition

Given a data frame students with columns name, grade, and gpa, find all students with a GPA above \( 3.5 \).

library(dplyr) honor_roll <- filter(students, gpa > 3.5)

Example 2: Multiple Conditions (AND)

Find seniors (\( \text{grade} == 12 \)) who also have a GPA above \( 3.5 \).

top_seniors <- filter(students, grade == 12, gpa > 3.5)

Example 3: OR and %in%

Find students who are in either the Art club or the Music club.

# Using the | (OR) operator creatives <- filter(students, club == "Art" | club == "Music") # Cleaner: using %in% creatives <- filter(students, club %in% c("Art", "Music"))

Example 4: Piping with filter()

Use the pipe operator \( \%>\% \) to chain filter() with other dplyr verbs for a complete analysis pipeline.

students %>% filter(grade == 12, gpa > 3.0) %>% select(name, gpa) %>% arrange(desc(gpa))

Handling NA Values

In R, NA (Not Available) represents missing data. Comparisons involving NA always return NA, not TRUE or FALSE. This means filter() automatically drops rows where the condition evaluates to NA.

# If some gpa values are NA, those rows are dropped filter(students, gpa > 3.0) # To explicitly keep NAs: filter(students, gpa > 3.0 | is.na(gpa)) # To find rows WITH missing data: filter(students, is.na(gpa))

Common Mistakes

✕ Using \( = \) instead of \( == \)
A single \( = \) is assignment, not comparison. Always use \( == \) to test equality inside filter().
✕ Forgetting quotes on strings
Writing \( \text{city} == \text{NYC} \) instead of \( \text{city} == \text{"NYC"} \) makes R look for a variable named NYC, not the text.
✕ Using \( \&\& \) instead of \( \& \)
\( \&\& \) is for scalar logic, not vectors. Inside filter(), use single \( \& \) for AND and single \( | \) for OR.

Summary of Key Patterns

Task Code Pattern
Single condition \( \text{filter(df, col > value)} \)
AND (both true) \( \text{filter(df, col1 > x, col2 == y)} \)
OR (either true) \( \text{filter(df, col == "a" | col == "b")} \)
Match from a set \( \text{filter(df, col \%in\% c("a","b","c"))} \)
Not equal \( \text{filter(df, col != "excluded")} \)
Find missing values \( \text{filter(df, is.na(col))} \)
Exclude missing values \( \text{filter(df, !is.na(col))} \)

Question 1 of 5

Which function from dplyr is used to select rows based on conditions?

Question 2 of 5

What does this code return?
\( \text{filter(df, age > 18, city == "Boston")} \)

Question 3 of 5

Which code correctly filters for rows where the color column equals "red" or "blue"?

Question 4 of 5

What happens to rows with NA in the filtered column when you run \( \text{filter(df, score > 80)} \)?

Question 5 of 5

What is wrong with this code?
\( \text{filter(students, grade = 12)} \)