The filter() Function
in R
Learn how to select specific rows from a data frame using logical conditions with the powerful dplyr filter() function.
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
Why filter() Matters
The Core Syntax
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
How to Apply filter()
Example 1: Single Condition
Given a data frame students with columns name, grade, and gpa, find all students with a GPA above \( 3.5 \).
Example 2: Multiple Conditions (AND)
Find seniors (\( \text{grade} == 12 \)) who also have a GPA above \( 3.5 \).
Example 3: OR and %in%
Find students who are in either the Art club or the Music club.
Example 4: Piping with filter()
Use the pipe operator \( \%>\% \) to chain filter() with other dplyr verbs for a complete analysis pipeline.
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.
Common Mistakes
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)} \)