dplyr Tutorial

Clean, transform and summarise data with dplyr

Practical lessons on filter, mutate, group_by, joins and more — with sample data and exercises.

dplyr cheat sheet Get help with your data

dplyr filter(): How to Filter Rows in R

Updated

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)
)
cities
citystateregiontime_zonepopulation_2010population_2020
New YorkNYNortheastEastern81758804
Los AngelesCAWestPacific37933899
ChicagoILMidwestCentral26962746
HoustonTXSouthCentral20992305
PhoenixAZWestMountain14461608
PhiladelphiaPANortheastEastern15261604
San AntonioTXSouthCentral13271435
San DiegoCAWestPacific13071387
DallasTXSouthCentral11981304
AustinTXSouthCentral790962

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:

citystateregiontime_zonepopulation_2010population_2020
HoustonTXSouthCentral20992305
San AntonioTXSouthCentral13271435
DallasTXSouthCentral11981304
AustinTXSouthCentral790962

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:

OperatorMeaningExample
==equal tostate == "TX"
!=not equal toregion != "South"
>greater thanpopulation_2020 > 2000
>=greater than or equal topopulation_2020 >= 2000
<less thanpopulation_2020 < 1000
<=less than or equal topopulation_2020 <= 1000
& or a commaANDstate == "TX", population_2020 > 1300
|ORstate == "CA" | state == "AZ"
!NOT!(state == "TX")
%in%is one of a liststate %in% c("CA", "AZ")
is.na()is missingis.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)
citystateregiontime_zonepopulation_2010population_2020
New YorkNYNortheastEastern81758804
Los AngelesCAWestPacific37933899
ChicagoILMidwestCentral26962746
HoustonTXSouthCentral20992305

The opposite, not equal, uses !=. This keeps every city outside the South:

cities |> filter(region != "South")
citystateregiontime_zonepopulation_2010population_2020
New YorkNYNortheastEastern81758804
Los AngelesCAWestPacific37933899
ChicagoILMidwestCentral26962746
PhoenixAZWestMountain14461608
PhiladelphiaPANortheastEastern15261604
San DiegoCAWestPacific13071387

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)
citystateregiontime_zonepopulation_2010population_2020
HoustonTXSouthCentral20992305
San AntonioTXSouthCentral13271435
DallasTXSouthCentral11981304

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")
citystateregiontime_zonepopulation_2010population_2020
Los AngelesCAWestPacific37933899
PhoenixAZWestMountain14461608
San DiegoCAWestPacific13071387

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"
)
citystateregiontime_zonepopulation_2010population_2020
Los AngelesCAWestPacific37933899
ChicagoILMidwestCentral26962746
HoustonTXSouthCentral20992305
PhoenixAZWestMountain14461608

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"))
citystateregiontime_zonepopulation_2010population_2020
New YorkNYNortheastEastern81758804
Los AngelesCAWestPacific37933899
PhoenixAZWestMountain14461608
San DiegoCAWestPacific13071387

To exclude values instead, put ! in front of the whole condition:

cities |> filter(!(state %in% c("TX", "CA")))
citystateregiontime_zonepopulation_2010population_2020
New YorkNYNortheastEastern81758804
ChicagoILMidwestCentral26962746
PhoenixAZWestMountain14461608
PhiladelphiaPANortheastEastern15261604

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))
citystateregiontime_zonepopulation_2010population_2020
HoustonTXSouthCentral20992305
PhoenixAZWestMountain14461608
PhiladelphiaPANortheastEastern15261604
San AntonioTXSouthCentral13271435

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)
citystatepopulation_2010population_2020
PhoenixAZ14461608
AustinTX790962

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))
citystateregiontime_zonepopulation_2010population_2020
San AntonioTXSouthCentral13271435
San DiegoCAWestPacific13071387

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)
)
rent
citymedian_rent
New York3400
Chicago1900
HoustonNA
Phoenix1650
Austin2000
DallasNA

Find the missing rows with is.na()

rent |> filter(is.na(median_rent))
citymedian_rent
HoustonNA
DallasNA

Remove missing rows with !is.na()

To filter out NA in R, add ! (NOT) in front:

rent |> filter(!is.na(median_rent))
citymedian_rent
New York3400
Chicago1900
Phoenix1650
Austin2000

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)
citymedian_rent
New York3400
Chicago1900
Austin2000

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)
citystateregiontime_zonepopulation_2010population_2020
New YorkNYNortheastEastern81758804
Los AngelesCAWestPacific37933899
ChicagoILMidwestCentral26962746
HoustonTXSouthCentral20992305

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))
citytime_zonepopulation_2020
ChicagoCentral2746
HoustonCentral2305
PhoenixMountain1608
San AntonioCentral1435
DallasCentral1304

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

TaskdplyrBase R
One conditionfilter(cities, state == "TX")cities[cities$state == "TX", ]
Two conditionsfilter(cities, state == "TX", population_2020 > 1300)cities[cities$state == "TX" & cities$population_2020 > 1300, ]
In a listfilter(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

MistakeWhat happensFix
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 variableQuote text: "TX"
filter(state == "tx")Zero rows, because text matching is case-sensitiveMatch the exact case, or use toupper(state) == "TX"
filter(x == NA)Zero rowsUse is.na(x)
filter(state == c("CA", "AZ"))Wrong rows, and sometimes a warningUse %in%
filter(a > 1 && b < 5)Error in recent R versionsUse a single & or a comma
Result "disappears"The pipeline printed but was not savedAssign it: texas <- cities |> filter(...)
filter behaves strangely or errorsAnother 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)
citystateregiontime_zonepopulation_2010population_2020
New YorkNYNortheastEastern81758804
Los AngelesCAWestPacific37933899

Exercise 2

Keep cities in the Pacific time zone.

Show answer
cities |> filter(time_zone == "Pacific")
citystateregiontime_zonepopulation_2010population_2020
Los AngelesCAWestPacific37933899
San DiegoCAWestPacific13071387

Exercise 3

Keep cities in the West or Northeast regions, using one condition.

Show answer
cities |> filter(region %in% c("West", "Northeast"))
citystateregiontime_zonepopulation_2010population_2020
New YorkNYNortheastEastern81758804
Los AngelesCAWestPacific37933899
PhoenixAZWestMountain14461608
PhiladelphiaPANortheastEastern15261604
San DiegoCAWestPacific13071387

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)
citypopulation_2010population_2020
Houston20992305
Phoenix14461608
San Antonio13271435
Dallas11981304
Austin790962

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)
citymedian_rent
New York3400
Chicago1900
Austin2000

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 is TRUE. 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 and between() for ranges.
  • Test for missing values with is.na(), never == NA.
  • filter() silently drops rows where the condition is NA.
  • 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.