3

Given a data.table, how can I select a set of columns using a variable?

Example:

df[, 1:3]

is OK, but

idx <- 1:3
df[, idx]

is not OK: column named "idx" does not exist.

How can I use idx to select the columns in the simplest possible way?

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • Your indexing works well for `iris[, idx]` – akrun Mar 22 '21 at 17:24
  • Are you sure you have run ```idx <- 1:3``` first? It should work. – bird Mar 22 '21 at 17:28
  • Error in `[.data.table`(df, , idx) : j (the 2nd argument inside [...]) is a single symbol but column name 'idx' is not found. Perhaps you intended DT[, ..idx]. This difference to data.frame is deliberate and explained in FAQ 1.1. – quesadagranja Mar 22 '21 at 17:28
  • Now I read... why should I use the double dot? – quesadagranja Mar 22 '21 at 17:29
  • If it is data.table. you need `df[, ..idx]` or `df[, idx, with = FALSE]` – akrun Mar 22 '21 at 17:44
  • [Extract columns from data table by numeric indices stored in a vector](https://stackoverflow.com/questions/49227360/extract-columns-from-data-table-by-numeric-indices-stored-in-a-vector); [Select / assign to data.table when variable names are stored in a character vector](https://stackoverflow.com/questions/12391950/select-assign-to-data-table-when-variable-names-are-stored-in-a-character-vect). From `?data.table`: `colNum = 2` "to refer vars in `j` from the outside of data use `..` prefix"; `DT[, ..colNum]` – Henrik Mar 22 '21 at 18:14

1 Answers1

2

We can use .. before the idx to select the columns in data.table or with = FALSE

library(data.table)
df[, ..idx]
df[, idx, with = FALSE]
akrun
  • 874,273
  • 37
  • 540
  • 662