Select columns in R data.table
How to select columns in R data.table by name, by variable, by pattern or by exclusion, what each form returns, and when plainer code is the better choice.
Column selection in data.table happens in the j argument of DT[i, j, by]. The package offers several ways to pick columns, and they differ in what they return and in how readable the code is to people who don't use data.table. This review covers the main forms, selecting columns by name or from a variable, and when a plainer approach suits shared code better.
Short verdict
For interactive work with fixed column names, DT[, .(col1, col2)] is concise and returns a data.table. When the names are stored in a variable, DT[, ..cols] or DT[, .SD, .SDcols = cols] are the documented, reliable options. The main benefit is short syntax that fits the rest of a data.table pipeline. The main tradeoff is that the syntax is specific to data.table, and the return type changes with small differences in how j is written. If the code will be maintained by people who mostly use base R or dplyr, or if it runs inside functions that receive plain data frames, standard data frame indexing such as df[cols] is often clearer.
What selecting a column actually changes
Selecting columns in j builds a new object and leaves the original table unchanged. Values, types and row order stay as they were, and only the set of columns differs. Dropping columns by reference with := NULL is a different operation because it modifies the original table in place. The most common source of confusion is the return type. Some forms return a data.table, while others return a bare vector.
| Form | Example | Returns |
| List of symbols | DT[, .(id, amount)] | data.table |
| list() spelled out | DT[, list(id, amount)] | data.table |
| Single bare symbol | DT[, amount] | vector |
| Character vector literal | DT[, c("id", "amount")] | data.table |
| Single character literal | DT[, "amount"] | data.table |
| Numeric positions | DT[, 1:2] | data.table |
| Double bracket | DT[["amount"]] | vector |
library(data.table)
DT <- data.table(
id = 1:3,
name = c("x", "y", "z"),
amount = c(10, 20, 30),
region = c("N", "S", "N")
)
DT[, .(id, amount)] # data.table with two columns
DT[, amount] # numeric vector
DT[, .(id, total = amount)] # select and rename in one step
Selecting columns by variable
Column names often come from a character vector, such as a function argument or a configuration value. data.table supports this in several ways. The .. prefix tells data.table to look up the variable in the calling scope instead of among the column names. with = FALSE is the older equivalent. .SDcols works well when you also want to apply a function to the selected columns.
cols <- c("id", "amount")
DT[, ..cols] # data.table
DT[, cols, with = FALSE] # data.table, older equivalent
DT[, .SD, .SDcols = cols] # data.table via .SD
col <- "amount"
DT[[col]] # vector
DT[, get(col)] # vector
A common mistake is writing DT[, cols] when cols is a variable rather than a column. data.table treats a single symbol in j as a column reference. When no column has that name, it raises an error that suggests ..cols instead of selecting the columns. get() and mget() also work inside j, but .. and .SDcols state the intent more clearly and are the forms the package documentation recommends for this task.
Excluding columns, ranges and patterns
DT[, !c("name", "region")] # all columns except these
DT[, !..cols] # exclude names held in a variable
DT[, id:amount] # contiguous range by name
DT[, .SD, .SDcols = patterns("^am")] # names matching a regex
DT[, .SD, .SDcols = is.numeric] # columns passing a test
Ranges and numeric positions depend on column order, so they can break silently if the upstream data adds or reorders columns. Name-based and pattern-based selection hold up better in scripts that run against changing inputs. Passing a function such as is.numeric to .SDcols is only supported in more recent releases. Check the documentation for your installed version before relying on it.
Selecting versus modifying in place
If you only need a smaller table for later steps and memory matters, you can drop the unwanted columns from the original by reference instead of creating a subset copy. This changes DT itself, and any other name that refers to the same table will also see the change. Use it only when the original layout is no longer needed.
DT[, c("name", "region") := NULL] # removes columns from DT in place
keep <- c("id", "amount")
small <- DT[, ..keep] # independent subset, DT unchanged
Readability and portability when sharing code
The selected result is an ordinary data.table, which also inherits from data.frame. It can be written out with fwrite or converted with as.data.frame, and the values stay exactly as they were. The more likely problem is readers of the code. The .. prefix, .() and .SDcols are unfamiliar to people outside data.table, and functions in packages that are not data.table-aware treat the object as a plain data frame, so data.table syntax inside them does not behave the same way. For shared or teaching code, a short comment or the base R equivalent makes the intent clear.
# data.table form
DT[, ..cols]
# base R equivalent on a data frame
as.data.frame(DT)[cols]
Gaps and what to verify
- No benchmark data was supplied, so this review makes no claims about the relative speed or memory use of the different selection forms.
- Some syntax, including the .. prefix and function-based .SDcols, was added in specific releases. Check your version with packageVersion("data.table") and confirm behavior in ?data.table.
- The examples follow documented behavior and were not run against a particular R or data.table version in preparing this review.