Select columns from an R data frame

How to select multiple columns in R by name, position or pattern with base R, subset(), dplyr and data.table, and how each choice holds up when code is shared.

Selecting several columns from a data frame is one of the most common operations in R, and there are several ways to do it. They differ in syntax, in what kind of object comes back, in how they react to missing column names, and in how easy the code is to read and reuse later. This review covers base R indexing, subset(), dplyr's select() and data.table, so you can pick the one that suits your situation.

No benchmark data, package version details or tested outputs were supplied for this review. The behavior described here follows the documented behavior of base R and the named packages. Check it against the versions you have installed, especially for package features that have changed over time.

Short recommendation

For quick, dependency-free work, base R bracket indexing by name is enough: it is explicit, always available, and fails loudly if a column is missing. If you already use the tidyverse, or you need pattern-based selection, renaming while selecting, or tolerance for optional columns, dplyr's select() is easier to read and maintain. The main tradeoff is that dplyr is an extra dependency and uses non-standard evaluation, which takes some care inside functions. data.table syntax makes sense only if your project already uses data.table. In every approach, select by name rather than by position unless the column order is guaranteed.

Base R: bracket indexing

The examples use the built-in mtcars data set, so they run without loading any data. To keep several columns by name, pass a character vector as the column index:

# Keep columns by name
mtcars[, c("mpg", "hp", "wt")]

# List-style indexing also returns a data frame
mtcars[c("mpg", "hp", "wt")]

# Keep columns by position (here: mpg, cyl, disp)
mtcars[, 1:3]
mtcars[, c(1, 4)]

Matrix-style indexing (with the comma) has one trap. When the result has only one column, a plain data frame is simplified to a vector by default. mtcars[, "mpg"] returns a numeric vector, not a data frame. If later code expects a data frame, write mtcars[, "mpg", drop = FALSE] or use list-style indexing, mtcars["mpg"]. This matters most when the column vector comes from a variable and can sometimes have length one. Tibbles behave differently: they do not drop to a vector with single-bracket indexing.

When the names are stored in a variable, the syntax stays the same:

keep <- c("mpg", "hp", "wt")
mtcars[, keep, drop = FALSE]

Dropping columns instead of keeping them

Negative indices remove columns by position. Base R has no equivalent for names, so mtcars[, -c("vs", "am")] produces an error. To drop by name, keep the complement:

# Drop by position
mtcars[, -c(8, 9)]

# Drop by name
mtcars[, !(names(mtcars) %in% c("vs", "am"))]
mtcars[setdiff(names(mtcars), c("vs", "am"))]

Selecting by pattern

Base R can select columns whose names match a regular expression by building a logical index from names():

# Columns whose names start with "d" (disp, drat)
mtcars[, grepl("^d", names(mtcars)), drop = FALSE]

Base R: subset()

subset() accepts unquoted column names, ranges and negation in its select argument, so interactive code reads closer to dplyr:

subset(mtcars, select = c(mpg, hp, wt))
subset(mtcars, select = mpg:disp)
subset(mtcars, select = -c(vs, am))

The R documentation for subset() describes it as a convenience for interactive use. Because of how it evaluates its arguments, it can behave unexpectedly inside functions, so use bracket indexing in programming code.

dplyr: select()

select() from the dplyr package takes bare column names, ranges, negation and a set of selection helpers. It always returns a data frame, even with only one column, so there is no single-column simplification to manage.

library(dplyr)

select(mtcars, mpg, hp, wt)
select(mtcars, mpg:disp)
select(mtcars, -vs, -am)

# Helpers
select(mtcars, starts_with("d"))
select(mtcars, ends_with("t"))
select(mtcars, contains("ar"))
select(mtcars, matches("^c"))

# Rename while selecting
select(mtcars, miles_per_gallon = mpg, hp)

When column names are held in a character vector, wrap the vector in all_of() or any_of(). all_of() raises an error if any name is missing. any_of() silently skips names that are not present, which is useful for optional columns but can hide typos.

cols <- c("mpg", "hp", "weight")

select(mtcars, any_of(cols))   # returns mpg and hp; "weight" is skipped
select(mtcars, all_of(cols))   # error: "weight" does not exist

Passing a bare character vector variable straight to select() without these wrappers is deprecated in current tidyselect and produces a warning, because it is ambiguous whether the name refers to a column or to an external variable.

data.table

If your data is already a data.table, use its own syntax rather than converting back and forth:

library(data.table)
dt <- as.data.table(mtcars)

dt[, .(mpg, hp, wt)]

cols <- c("mpg", "hp", "wt")
dt[, ..cols]

Note that as.data.table() drops the row names of mtcars (the car models) unless you request them with its keep.rownames argument.

What selection changes, and what it leaves alone

  • It creates a new object. The original data frame is unchanged unless you assign the result back to the same name.
  • Columns appear in the order you specify, not their original order. Selecting c("wt", "mpg") puts wt first, which also makes selection a simple way to reorder columns.
  • Rows are not filtered. All rows are kept; only the set of columns changes.
  • Values and column types are untouched. Names change only if you rename explicitly, for example in dplyr's select().
  • The returned object can differ by method: base R matrix-style indexing on a single column can return a vector, while select() and list-style indexing always return a data frame.

Comparing the approaches

Approach | Keep by name | Drop by name | Pattern helpers | Missing name | Extra package
Base R [ , ] | Yes | Via %in% or setdiff() | Via grepl() | Error | No
subset() | Yes, unquoted | Yes, with - | No | Error | No
dplyr select() | Yes, unquoted or all_of()/any_of() | Yes, with - | Yes | Error, or skipped with any_of() | dplyr
data.table | Yes, .() or ..cols | Yes | Not built into select syntax | Error | data.table

Will the code stay usable when it is shared or rerun?

For column selection, usability depends less on how the output looks and more on whether the code still does the right thing when someone else runs it on slightly different data. Four factors matter most:

  • Names versus positions: mtcars[, 1:3] silently selects different columns if the source column order changes. Name-based selection either selects the intended columns or fails visibly.
  • Missing columns: base R, subset() and all_of() stop with an error, which is usually what you want in a pipeline. any_of() continues without the missing column, so use it only when the column really is optional.
  • Dependencies: base R code runs anywhere R is installed. dplyr or data.table code needs the package installed, and results can shift between package versions, so recording package versions helps others reproduce your work.
  • Use inside functions: subset() and bare names in select() rely on non-standard evaluation. In reusable functions, pass column names as character vectors and use bracket indexing, all_of(), or dplyr's documented embracing syntax ({{ }}) for column arguments.

If readers of your code may not know the tidyverse, a short comment or a base R equivalent next to helper-heavy select() calls makes the intent clear.

Limits of this overview

This overview covers selecting columns, not filtering rows or reshaping data. It does not compare performance, because no measurements were available. Any speed differences between base R, dplyr and data.table depend on data size and package versions and should be measured in your own environment. Exact warning wording and deprecation timing also depend on the installed package versions.