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 select(): How to Select Columns in R

Updated

Real data often has more columns than you need. select() keeps the ones you want, drops the rest and puts them in the order you choose.

What does select() do?

select() is the dplyr function for working with columns. You give it a data frame and the columns you want, and it returns a new data frame containing only those columns. It never changes the original.

select(data, column1, column2, ...)

Because the data frame is the first argument, select() works naturally with the pipe, which you met in the pipe operator lesson. The rest of this dplyr tutorial uses the native pipe |>:

data |> select(column1, column2)

If you want to choose rows instead, see dplyr filter. This lesson is only about columns.

Sample data

This lesson extends the table of ten large US cities with more columns, so there is plenty to select from. Populations are rounded Census figures in thousands, for practice. Run this code to create it:

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: six columns, ten rows
citystateregiontime_zonepopulation_2010population_2020
New YorkNYNortheastEastern81758804
Los AngelesCAWestPacific37933899
ChicagoILMidwestCentral26962746
HoustonTXSouthCentral20992305
PhoenixAZWestMountain14461608
PhiladelphiaPANortheastEastern15261604
San AntonioTXSouthCentral13271435
San DiegoCAWestPacific13071387
DallasTXSouthCentral11981304
AustinTXSouthCentral790962

There are four text columns (city, state, region, time_zone) and two number columns. Several examples below show only the first five rows to save space. R would print all ten.

Select one column

Name the column you want, without quotes:

cities |> select(city)
city
New York
Los Angeles
Chicago
Houston
Phoenix

The result is still a data frame, now with one column. Quoted names such as select("city") also work, but the unquoted style is the convention in dplyr.

Select multiple columns

To select multiple columns in R, separate the names with commas:

cities |> select(city, state, population_2020)
citystatepopulation_2020
New YorkNY8804
Los AngelesCA3899
ChicagoIL2746
HoustonTX2305
PhoenixAZ1608

The order you type is the order you get. This makes select() useful for reordering too:

cities |> select(population_2020, city)
population_2020city
8804New York
3899Los Angeles
2746Chicago
2305Houston
1608Phoenix

Select a range of columns

A colon selects every column from one name to another, in the order they appear in the data:

cities |> select(city:region)
citystateregion
New YorkNYNortheast
Los AngelesCAWest
ChicagoILMidwest
HoustonTXSouth
PhoenixAZWest

This returns city, state and region. It is a quick way to take many neighbouring columns without typing each one.

Select by position

You can also use column numbers. This takes the first and last columns:

cities |> select(1, 6)
citypopulation_2020
New York8804
Los Angeles3899
Chicago2746
Houston2305
Phoenix1608

Use this only for quick exploration. If the column order of your data changes, position numbers silently pick the wrong columns, while names keep working.

Drop columns

A minus sign in front of a name removes that column and keeps everything else:

cities |> select(-time_zone)
citystateregionpopulation_2010population_2020
New YorkNYNortheast81758804
Los AngelesCAWest37933899
ChicagoILMidwest26962746
HoustonTXSouth20992305
PhoenixAZWest14461608

To drop several columns at once, wrap them in c() after the minus:

cities |> select(-c(state, time_zone))
cityregionpopulation_2010population_2020
New YorkNortheast81758804
Los AngelesWest37933899
ChicagoMidwest26962746
HoustonSouth20992305
PhoenixWest14461608

You can also drop a range, with parentheses around it: select(-(state:time_zone)). The exclamation mark ! works the same way as the minus sign: select(!time_zone).

Select by name pattern or type

When a data set has dozens of columns, typing every name is slow. dplyr provides tidyselect helpers that choose columns by pattern or by type. Put them inside select().

HelperSelects columns that...Example
starts_with()begin with some textstarts_with("population")
ends_with()end with some textends_with("2020")
contains()include some text anywherecontains("zone")
matches()match a regular expressionmatches("region|zone")
num_range()have a prefix plus a numbernum_range("population_", 2010:2020)
everything()are all columnseverything()
last_col()is the final columnlast_col()
where()pass a test on their typewhere(is.numeric)

starts_with()

cities |> select(city, starts_with("population"))
citypopulation_2010population_2020
New York81758804
Los Angeles37933899
Chicago26962746
Houston20992305
Phoenix14461608

This is perfect for data with column families, such as population_2010 and population_2020. A new column called population_2030 would be picked up automatically.

ends_with()

cities |> select(city, ends_with("2020"))
citypopulation_2020
New York8804
Los Angeles3899
Chicago2746
Houston2305
Phoenix1608

contains()

cities |> select(city, contains("zone"))
citytime_zone
New YorkEastern
Los AngelesPacific
ChicagoCentral
HoustonCentral
PhoenixMountain

These helpers ignore upper and lower case by default, so starts_with("Population") gives the same result. Add ignore.case = FALSE if you want an exact case match.

matches()

For more complex patterns, matches() accepts a regular expression. This one picks columns that contain either "region" or "zone":

cities |> select(city, matches("region|zone"))
cityregiontime_zone
New YorkNortheastEastern
Los AngelesWestPacific
ChicagoMidwestCentral
HoustonSouthCentral
PhoenixWestMountain

num_range()

When column names are a prefix followed by numbers, num_range() builds the names for you:

cities |> select(city, num_range("population_", c(2010, 2020)))
citypopulation_2010population_2020
New York81758804
Los Angeles37933899
Chicago26962746
Houston20992305
Phoenix14461608

everything() and last_col()

everything() means "all the remaining columns". It is most useful for reordering, covered below. last_col() picks the final column without needing its name:

cities |> select(city, last_col())
citypopulation_2020
New York8804
Los Angeles3899
Chicago2746
Houston2305
Phoenix1608

where(): select by column type

where() takes a function that returns TRUE or FALSE for each column. Use it to select all numeric columns in R:

cities |> select(where(is.numeric))
population_2010population_2020
81758804
37933899
26962746
20992305
14461608

Or all text columns:

cities |> select(where(is.character))
citystateregiontime_zone
New YorkNYNortheastEastern
Los AngelesCAWestPacific
ChicagoILMidwestCentral
HoustonTXSouthCentral
PhoenixAZWestMountain

Other test functions that work here include is.factor, is.logical and is.Date. You will meet where() again in the dplyr across lesson.

Combine helpers

You can mix names, ranges, helpers and minus signs in one select(). dplyr reads from left to right:

cities |> select(city, where(is.numeric), -population_2010)
citypopulation_2020
New York8804
Los Angeles3899
Chicago2746
Houston2305
Phoenix1608

This says: keep city, add every numeric column, then remove population_2010. Another example, keeping the location columns but not the numbers:

cities |> select(city:time_zone, -state)
cityregiontime_zone
New YorkNortheastEastern
Los AngelesWestPacific
ChicagoMidwestCentral
HoustonSouthCentral
PhoenixWestMountain

Reorder columns

To move a column to the front and keep the rest in their current order, name it first and finish with everything():

cities |> select(population_2020, everything())
population_2020citystateregiontime_zonepopulation_2010
8804New YorkNYNortheastEastern8175
3899Los AngelesCAWestPacific3793
2746ChicagoILMidwestCentral2696
2305HoustonTXSouthCentral2099
1608PhoenixAZWestMountain1446

dplyr also has relocate(), which is designed for moving columns. It is often clearer because you do not need to list the other columns:

cities |> relocate(population_2020, .after = city)
citypopulation_2020stateregiontime_zonepopulation_2010
New York8804NYNortheastEastern8175
Los Angeles3899CAWestPacific3793
Chicago2746ILMidwestCentral2696
Houston2305TXSouthCentral2099
Phoenix1608AZWestMountain1446

Use .before = or .after = to say where the column should go. Without either, relocate() moves it to the front.

Rename while selecting

You can give a column a new name inside select() by writing new_name = old_name:

cities |> select(city, population = population_2020)
citypopulation
New York8804
Los Angeles3899
Chicago2746
Houston2305
Phoenix1608

Be aware that select() keeps only the columns you list. To rename columns and keep all the others, use rename(), which has its own lesson: dplyr rename.

Select with a vector of names

Sometimes the column names are stored in a variable, for example when they come from a user input or a config. Wrap that vector in all_of() or any_of():

wanted <- c("city", "state")

cities |> select(all_of(wanted))
citystate
New YorkNY
Los AngelesCA
ChicagoIL
HoustonTX
PhoenixAZ

The difference between the two helpers is how they treat a name that does not exist:

  • all_of() is strict. If a name is missing, R stops with an error. Use it when a missing column would be a bug.
  • any_of() is forgiving. It silently skips names that are not found. Use it when some columns may or may not be present.
wanted <- c("city", "mayor")

cities |> select(any_of(wanted))   # returns only city
cities |> select(all_of(wanted))   # error: column `mayor` doesn't exist

select() vs pull()

select() always returns a data frame. If you need the values of a column as a plain vector, for example to pass to mean(), use pull():

cities |> pull(population_2020)
[1] 8804 3899 2746 2305 1608 1604 1435 1387 1304  962
cities |>
  filter(state == "CA") |>
  pull(city)
[1] "Los Angeles" "San Diego"

A simple rule: if the next step expects a table, use select(). If it expects a vector of values, use pull().

select() in a pipeline

select() is often combined with other dplyr verbs. This example finds Texas cities, keeps the name and both population columns, and sorts by the 2020 population, largest first:

cities |>
  filter(state == "TX") |>
  select(city, starts_with("population")) |>
  arrange(desc(population_2020))
citypopulation_2010population_2020
Houston20992305
San Antonio13271435
Dallas11981304
Austin790962

A good habit is to put select() early in a long pipeline. Dropping columns you do not need keeps later steps fast and makes the output easier to read. Save the result with <- if you want to reuse it:

tx_cities <- cities |>
  filter(state == "TX") |>
  select(city, starts_with("population"))

dplyr select vs base R

TaskdplyrBase R
Pick two columnsselect(cities, city, state)cities[, c("city", "state")]
Drop a columnselect(cities, -time_zone)cities[, names(cities) != "time_zone"]
Columns starting with textselect(cities, starts_with("pop"))cities[, grepl("^pop", names(cities))]
All numeric columnsselect(cities, where(is.numeric))cities[, sapply(cities, is.numeric)]
One column as a vectorpull(cities, city)cities$city

The dplyr versions read like instructions, and the helpers remove the need for grepl() and sapply().

Common errors

Message or symptomCauseFix
unused argumentThe select() from the MASS package is masking dplyr'sWrite dplyr::select(...), or load dplyr after MASS
Can't select columns that don't existA typo, or wrong capitalisation. Column names are case-sensitiveCheck the names with names(cities) (wording of the message varies by version)
Using an external vector in selections was deprecatedYou passed a variable holding names directlyWrap it: select(all_of(wanted))
The original data still has all columnsselect() returns a new table and does not change the old oneAssign it: small <- cities |> select(city, state)
Error when calling starts_with() on its ownTidyselect helpers only work inside functions that support them, such as select()Use them inside select(), across() or similar

Practice exercises

Use the cities table. Try each one before opening the answer.

Exercise 1

Select the city and region columns.

Show answer
cities |> select(city, region)
cityregion
New YorkNortheast
Los AngelesWest
ChicagoMidwest
HoustonSouth
PhoenixWest

Exercise 2

Show every column except state and time_zone.

Show answer
cities |> select(-c(state, time_zone))
cityregionpopulation_2010population_2020
New YorkNortheast81758804
Los AngelesWest37933899
ChicagoMidwest26962746
HoustonSouth20992305
PhoenixWest14461608

Exercise 3

Select city plus every numeric column, using a helper instead of typing the numeric names.

Show answer
cities |> select(city, where(is.numeric))
citypopulation_2010population_2020
New York81758804
Los Angeles37933899
Chicago26962746
Houston20992305
Phoenix14461608

Exercise 4

Move region to the first position and keep all other columns.

Show answer
cities |> select(region, everything())

or, with relocate():

cities |> relocate(region)
regioncitystatetime_zonepopulation_2010population_2020
NortheastNew YorkNYEastern81758804
WestLos AngelesCAPacific37933899
MidwestChicagoILCentral26962746
SouthHoustonTXCentral20992305
WestPhoenixAZMountain14461608

dplyr FAQ

How do I select multiple columns in R with dplyr?

List the column names inside select(), separated by commas, for example select(cities, city, state, population_2020). Use a colon to take a range, such as city:region.

How do I drop a column in dplyr?

Put a minus sign before the column name: select(cities, -time_zone). To drop several, use select(cities, -c(state, time_zone)).

How do I select columns by part of their name?

Use the tidyselect helpers starts_with(), ends_with() and contains(), for example select(cities, starts_with("population")).

What is the difference between select() and pull()?

select() returns a data frame, even if it has one column. pull() returns the values of one column as a plain vector.

Why do I get "unused argument" when I use select()?

Another package, usually MASS, has its own select() and has masked the dplyr one. Call dplyr::select() explicitly or load dplyr last.

How do I move a column to the front?

Name it first and add everything(): select(cities, population_2020, everything()). You can also use relocate().

Key points

  • select() chooses columns. Use filter() for rows.
  • List names with commas, take ranges with :, and drop columns with -.
  • starts_with(), ends_with(), contains() and matches() select by name pattern. where() selects by type.
  • Use everything() or relocate() to reorder columns.
  • Use all_of() or any_of() when names are stored in a vector.
  • pull() returns a vector, while select() returns a data frame.

Now that you can choose columns, learn how to choose rows with dplyr filter. If you want a refresher on chaining steps, revisit the pipe operator lesson.