dplyr filter(): How to Filter Rows in R
filter() keeps the rows that meet a condition and drops the rest. It is the dplyr function you will use most often, so this lesson starts with one tiny condition and builds up from there.
What does filter() do?
filter() is the dplyr function for working with rows. You give it a data frame and a condition. For each row, R checks whether the condition is TRUE or FALSE, and filter() keeps only the TRUE rows. All columns stay, and the original data is not changed.
filter(data, condition)
It pairs with the pipe, covered in the pipe operator lesson:
data |> filter(condition)
To choose columns instead of rows, use dplyr select. Together, select() and filter() let you cut a table down both ways. This page belongs to our dplyr tutorial.
Sample data
We use the same ten US cities from the previous lesson. Populations are rounded Census figures in thousands, for practice.
library(dplyr)
cities <- tibble(
city = c("New York", "Los Angeles", "Chicago", "Houston", "Phoenix",
"Philadelphia", "San Antonio", "San Diego", "Dallas", "Austin"),
state = c("NY", "CA", "IL", "TX", "AZ", "PA", "TX", "CA", "TX", "TX"),
region = c("Northeast", "West", "Midwest", "South", "West",
"Northeast", "South", "West", "South", "South"),
time_zone = c("Eastern", "Pacific", "Central", "Central", "Mountain",
"Eastern", "Central", "Pacific", "Central", "Central"),
population_2010 = c(8175, 3793, 2696, 2099, 1446, 1526, 1327, 1307, 1198, 790),
population_2020 = c(8804, 3899, 2746, 2305, 1608, 1604, 1435, 1387, 1304, 962)
)
| city | state | region | time_zone | population_2010 | population_2020 |
|---|---|---|---|---|---|
| New York | NY | Northeast | Eastern | 8175 | 8804 |
| Los Angeles | CA | West | Pacific | 3793 | 3899 |
| Chicago | IL | Midwest | Central | 2696 | 2746 |
| Houston | TX | South | Central | 2099 | 2305 |
| Phoenix | AZ | West | Mountain | 1446 | 1608 |
| Philadelphia | PA | Northeast | Eastern | 1526 | 1604 |
| San Antonio | TX | South | Central | 1327 | 1435 |
| San Diego | CA | West | Pacific | 1307 | 1387 |
| Dallas | TX | South | Central | 1198 | 1304 |
| Austin | TX | South | Central | 790 | 962 |
Your first filter
Start with the simplest question: which of these cities are in Texas?
cities |> filter(state == "TX")
Inside filter(), state == "TX" is the condition. R tests it on every row. Houston has state "TX", so it passes. New York has "NY", so it fails. The result:
| city | state | region | time_zone | population_2010 | population_2020 |
|---|---|---|---|---|---|
| Houston | TX | South | Central | 2099 | 2305 |
| San Antonio | TX | South | Central | 1327 | 1435 |
| Dallas | TX | South | Central | 1198 | 1304 |
| Austin | TX | South | Central | 790 | 962 |
Two things to notice. First, a double equals sign == means "is equal to". A single = would be an assignment and gives an error. Second, text values go in quotes and must match exactly, including capital letters. "tx" would not match "TX".
Comparison operators
Conditions are built from a small set of operators. Here is the full toolkit:
| Operator | Meaning | Example |
|---|---|---|
== | equal to | state == "TX" |
!= | not equal to | region != "South" |
> | greater than | population_2020 > 2000 |
>= | greater than or equal to | population_2020 >= 2000 |
< | less than | population_2020 < 1000 |
<= | less than or equal to | population_2020 <= 1000 |
& or a comma | AND | state == "TX", population_2020 > 1300 |
| | OR | state == "CA" | state == "AZ" |
! | NOT | !(state == "TX") |
%in% | is one of a list | state %in% c("CA", "AZ") |
is.na() | is missing | is.na(median_rent) |
Filter numbers
Which cities had more than two million people in 2020? The unit is thousands, so that is 2000:
cities |> filter(population_2020 > 2000)
| city | state | region | time_zone | population_2010 | population_2020 |
|---|---|---|---|---|---|
| New York | NY | Northeast | Eastern | 8175 | 8804 |
| Los Angeles | CA | West | Pacific | 3793 | 3899 |
| Chicago | IL | Midwest | Central | 2696 | 2746 |
| Houston | TX | South | Central | 2099 | 2305 |
The opposite, not equal, uses !=. This keeps every city outside the South:
cities |> filter(region != "South")
| city | state | region | time_zone | population_2010 | population_2020 |
|---|---|---|---|---|---|
| New York | NY | Northeast | Eastern | 8175 | 8804 |
| Los Angeles | CA | West | Pacific | 3793 | 3899 |
| Chicago | IL | Midwest | Central | 2696 | 2746 |
| Phoenix | AZ | West | Mountain | 1446 | 1608 |
| Philadelphia | PA | Northeast | Eastern | 1526 | 1604 |
| San Diego | CA | West | Pacific | 1307 | 1387 |
Numbers are never put in quotes, and you can use == with them too, such as population_2020 == 962. With decimals, prefer > and <, because computers store decimals with tiny rounding errors.
Multiple conditions: AND
To filter with multiple conditions in R, separate them with commas. A row must meet all of them to stay:
cities |> filter(state == "TX", population_2020 > 1300)
| city | state | region | time_zone | population_2010 | population_2020 |
|---|---|---|---|---|---|
| Houston | TX | South | Central | 2099 | 2305 |
| San Antonio | TX | South | Central | 1327 | 1435 |
| Dallas | TX | South | Central | 1198 | 1304 |
This asks for Texas cities and more than 1.3 million people. Austin is in Texas but has only 962 thousand, so it is dropped. The comma is shorthand for &, so this does exactly the same thing:
cities |> filter(state == "TX" & population_2020 > 1300)
Use a single &, never &&. The double version looks at only one value, and in R 4.3 and newer it raises an error inside filter().
Multiple conditions: OR
Use | (the vertical bar) when a row only has to meet one of the conditions:
cities |> filter(state == "CA" | state == "AZ")
| city | state | region | time_zone | population_2010 | population_2020 |
|---|---|---|---|---|---|
| Los Angeles | CA | West | Pacific | 3793 | 3899 |
| Phoenix | AZ | West | Mountain | 1446 | 1608 |
| San Diego | CA | West | Pacific | 1307 | 1387 |
Cities in California or Arizona. The commas in the AND example cannot do this, so remember: comma = AND, bar = OR.
Mixing AND and OR
When you combine both, use parentheses to make the order clear. Suppose you want cities that are either very big (over two million) or in Arizona, but not in the Eastern time zone:
cities |> filter(
population_2020 > 2000 | state == "AZ",
time_zone != "Eastern"
)
| city | state | region | time_zone | population_2010 | population_2020 |
|---|---|---|---|---|---|
| Los Angeles | CA | West | Pacific | 3793 | 3899 |
| Chicago | IL | Midwest | Central | 2696 | 2746 |
| Houston | TX | South | Central | 2099 | 2305 |
| Phoenix | AZ | West | Mountain | 1446 | 1608 |
The first line is an OR group. The comma then adds an AND with the second condition. New York was big enough to pass the first test, but it is in the Eastern time zone, so it was removed.
When writing one long condition, add parentheses yourself to avoid surprises: (a | b) & c. Without them, R evaluates & before |.
Filter with %in%
Writing state == "CA" | state == "AZ" | state == "NY" gets tedious. The %in% operator checks whether a value is one of a list, so you filter by multiple values in R with one condition:
cities |> filter(state %in% c("CA", "AZ", "NY"))
| city | state | region | time_zone | population_2010 | population_2020 |
|---|---|---|---|---|---|
| New York | NY | Northeast | Eastern | 8175 | 8804 |
| Los Angeles | CA | West | Pacific | 3793 | 3899 |
| Phoenix | AZ | West | Mountain | 1446 | 1608 |
| San Diego | CA | West | Pacific | 1307 | 1387 |
To exclude values instead, put ! in front of the whole condition:
cities |> filter(!(state %in% c("TX", "CA")))
| city | state | region | time_zone | population_2010 | population_2020 |
|---|---|---|---|---|---|
| New York | NY | Northeast | Eastern | 8175 | 8804 |
| Chicago | IL | Midwest | Central | 2696 | 2746 |
| Phoenix | AZ | West | Mountain | 1446 | 1608 |
| Philadelphia | PA | Northeast | Eastern | 1526 | 1604 |
Do not write state == c("CA", "AZ"). R would compare the first city to "CA", the second to "AZ", the third to "CA" again, and so on. That produces wrong results without any error. Always use %in% for lists.
Filter a range with between()
To keep numbers inside a range, between(x, left, right) is shorter than writing two conditions. Both ends are included:
cities |> filter(between(population_2020, 1400, 2500))
| city | state | region | time_zone | population_2010 | population_2020 |
|---|---|---|---|---|---|
| Houston | TX | South | Central | 2099 | 2305 |
| Phoenix | AZ | West | Mountain | 1446 | 1608 |
| Philadelphia | PA | Northeast | Eastern | 1526 | 1604 |
| San Antonio | TX | South | Central | 1327 | 1435 |
This is the same as population_2020 >= 1400 & population_2020 <= 2500. Do not write it like a maths class: 1400 < population_2020 < 2500 is not valid in R.
Compare two columns
A condition can use more than one column. Which cities grew by more than 10% between 2010 and 2020? That means the 2020 value is above the 2010 value multiplied by 1.1:
cities |> filter(population_2020 > population_2010 * 1.1)
| city | state | population_2010 | population_2020 |
|---|---|---|---|
| Phoenix | AZ | 1446 | 1608 |
| Austin | TX | 790 | 962 |
Only Phoenix and Austin qualify. Calculations are allowed inside the condition. To store a growth figure in a new column instead, you would use mutate(), covered in the dplyr mutate lesson.
Filter text patterns
Sometimes you do not know the full text, only part of it. Base R's grepl() tests whether text matches a pattern. The symbol ^ means "at the start":
cities |> filter(grepl("^San", city))
| city | state | region | time_zone | population_2010 | population_2020 |
|---|---|---|---|---|---|
| San Antonio | TX | South | Central | 1327 | 1435 |
| San Diego | CA | West | Pacific | 1307 | 1387 |
This returns the cities whose names start with "San". The base function startsWith(city, "San") does the same without needing pattern symbols. If you use the stringr package, str_detect(city, "^San") is a popular alternative.
Filter missing values (NA)
Real data often has gaps. In R, a missing value is written NA. Here is a small, made-up rent survey with two missing values. The numbers are practice values, not real statistics:
rent <- tibble(
city = c("New York", "Chicago", "Houston", "Phoenix", "Austin", "Dallas"),
median_rent = c(3400, 1900, NA, 1650, 2000, NA)
)
| city | median_rent |
|---|---|
| New York | 3400 |
| Chicago | 1900 |
| Houston | NA |
| Phoenix | 1650 |
| Austin | 2000 |
| Dallas | NA |
Find the missing rows with is.na()
rent |> filter(is.na(median_rent))
| city | median_rent |
|---|---|
| Houston | NA |
| Dallas | NA |
Remove missing rows with !is.na()
To filter out NA in R, add ! (NOT) in front:
rent |> filter(!is.na(median_rent))
| city | median_rent |
|---|---|
| New York | 3400 |
| Chicago | 1900 |
| Phoenix | 1650 |
| Austin | 2000 |
Why == NA does not work
An NA means "unknown", and asking whether an unknown equals another unknown gives an unknown answer, not TRUE. So this returns nothing:
rent |> filter(median_rent == NA)
# A tibble: 0 × 2
# ℹ 2 variables: city <chr>, median_rent <dbl>
Always use is.na().
filter() quietly drops NA rows
When a condition evaluates to NA, filter() treats it as not TRUE and removes the row. That means a simple comparison also discards the missing rows:
rent |> filter(median_rent > 1800)
| city | median_rent |
|---|---|
| New York | 3400 |
| Chicago | 1900 |
| Austin | 2000 |
Houston and Dallas vanished, not because they are below 1800, but because their rent is unknown. If you want to keep unknowns, say so explicitly: filter(median_rent > 1800 | is.na(median_rent)).
Filter within groups
Since dplyr 1.1.0, filter() accepts a .by argument that runs the condition separately inside each group. This keeps the biggest city in each region:
cities |> filter(population_2020 == max(population_2020), .by = region)
| city | state | region | time_zone | population_2010 | population_2020 |
|---|---|---|---|---|---|
| New York | NY | Northeast | Eastern | 8175 | 8804 |
| Los Angeles | CA | West | Pacific | 3793 | 3899 |
| Chicago | IL | Midwest | Central | 2696 | 2746 |
| Houston | TX | South | Central | 2099 | 2305 |
Without .by, max(population_2020) would be the single largest value in the whole table. Grouping has its own lesson: dplyr group_by and summarise. For taking the top rows per group, dplyr slice is often simpler.
filter() in a pipeline
Real analyses chain several steps. This finds cities in the Central or Mountain time zones with more than 1.3 million people, keeps three columns, and sorts them largest first:
cities |>
filter(time_zone %in% c("Central", "Mountain"), population_2020 > 1300) |>
select(city, time_zone, population_2020) |>
arrange(desc(population_2020))
| city | time_zone | population_2020 |
|---|---|---|
| Chicago | Central | 2746 |
| Houston | Central | 2305 |
| Phoenix | Mountain | 1608 |
| San Antonio | Central | 1435 |
| Dallas | Central | 1304 |
Filtering early, before other steps, means later steps have fewer rows to process. To keep the result, assign it:
big_central <- cities |>
filter(time_zone == "Central", population_2020 > 1300)
Remember that filter() does not change cities. It returns a new table.
dplyr filter vs base R
| Task | dplyr | Base R |
|---|---|---|
| One condition | filter(cities, state == "TX") | cities[cities$state == "TX", ] |
| Two conditions | filter(cities, state == "TX", population_2020 > 1300) | cities[cities$state == "TX" & cities$population_2020 > 1300, ] |
| In a list | filter(cities, state %in% c("CA", "AZ")) | cities[cities$state %in% c("CA", "AZ"), ] |
| Using subset() | filter(cities, state == "TX") | subset(cities, state == "TX") |
The base R version needs cities$ before every column and a trailing comma. With filter() you write the column name once. A bonus: on data with NA values, the base bracket style creates rows full of NA, while filter() simply drops them.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
filter(state = "TX") | Error that mentions a named input and suggests == | Use == for comparison |
filter(state == TX) | Error: object 'TX' not found, because R thinks TX is a column or variable | Quote text: "TX" |
filter(state == "tx") | Zero rows, because text matching is case-sensitive | Match the exact case, or use toupper(state) == "TX" |
filter(x == NA) | Zero rows | Use is.na(x) |
filter(state == c("CA", "AZ")) | Wrong rows, and sometimes a warning | Use %in% |
filter(a > 1 && b < 5) | Error in recent R versions | Use a single & or a comma |
| Result "disappears" | The pipeline printed but was not saved | Assign it: texas <- cities |> filter(...) |
filter behaves strangely or errors | Another package masked it. The stats package also has a filter() | Write dplyr::filter() |
Practice exercises
Use the cities and rent tables. Try each one before opening the answer.
Exercise 1
Keep cities with a 2020 population above 3,000 (thousand).
Show answer
cities |> filter(population_2020 > 3000)
| city | state | region | time_zone | population_2010 | population_2020 |
|---|---|---|---|---|---|
| New York | NY | Northeast | Eastern | 8175 | 8804 |
| Los Angeles | CA | West | Pacific | 3793 | 3899 |
Exercise 2
Keep cities in the Pacific time zone.
Show answer
cities |> filter(time_zone == "Pacific")
| city | state | region | time_zone | population_2010 | population_2020 |
|---|---|---|---|---|---|
| Los Angeles | CA | West | Pacific | 3793 | 3899 |
| San Diego | CA | West | Pacific | 1307 | 1387 |
Exercise 3
Keep cities in the West or Northeast regions, using one condition.
Show answer
cities |> filter(region %in% c("West", "Northeast"))
| city | state | region | time_zone | population_2010 | population_2020 |
|---|---|---|---|---|---|
| New York | NY | Northeast | Eastern | 8175 | 8804 |
| Los Angeles | CA | West | Pacific | 3793 | 3899 |
| Phoenix | AZ | West | Mountain | 1446 | 1608 |
| Philadelphia | PA | Northeast | Eastern | 1526 | 1604 |
| San Diego | CA | West | Pacific | 1307 | 1387 |
Exercise 4
Find cities that grew by more than 8% from 2010 to 2020. Show the city and both populations.
Show answer
cities |>
filter(population_2020 > population_2010 * 1.08) |>
select(city, population_2010, population_2020)
| city | population_2010 | population_2020 |
|---|---|---|
| Houston | 2099 | 2305 |
| Phoenix | 1446 | 1608 |
| San Antonio | 1327 | 1435 |
| Dallas | 1198 | 1304 |
| Austin | 790 | 962 |
Exercise 5
From the rent table, keep cities with a known median rent above 1,700.
Show answer
rent |> filter(!is.na(median_rent), median_rent > 1700)
| city | median_rent |
|---|---|
| New York | 3400 |
| Chicago | 1900 |
| Austin | 2000 |
The !is.na() part is optional here, because filter() drops NA rows anyway, but it makes your intention clear to readers.
dplyr FAQ
How do I filter rows in R with dplyr?
Pass the data frame and a condition to filter(), for example filter(cities, state == "TX"). Only rows where the condition is TRUE are kept.
How do I filter with multiple conditions in dplyr?
Separate conditions with a comma or use & for AND, for example filter(cities, state == "TX", population_2020 > 1300). Use | for OR.
How do I filter by a list of values?
Use %in%: filter(cities, state %in% c("CA", "AZ", "NY")). Put ! before the condition to exclude those values instead.
How do I filter out NA values in R?
Use !is.na(): filter(data, !is.na(column)). To keep only the missing rows, use is.na(column).
Why does filter() return zero rows?
Common causes are a typo or wrong capitalisation in a text value, comparing with == NA instead of is.na(), or conditions that cannot all be true at once.
What is the difference between filter() and subset()?
Both keep rows that meet a condition and both drop rows where the condition is NA. filter() is part of dplyr, accepts several comma-separated conditions, supports .by for group-wise filtering and fits naturally into pipelines. subset() is base R.
Key points
filter()keeps rows where the condition isTRUE. Columns are untouched.- Use
==to compare, and put text in quotes. - A comma or
&means AND. A vertical bar|means OR. Add parentheses when you mix them. - Use
%in%for lists of values andbetween()for ranges. - Test for missing values with
is.na(), never== NA. filter()silently drops rows where the condition isNA.- Assign the result to keep it, because
filter()does not change the original.
Next, learn how to create and change columns with dplyr mutate. To revisit choosing columns, see dplyr select.