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?
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]
base R, then df[idx] would work where df is a data.frame
iris[, idx]idx <- 1:3first? It should work.[.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.df[, ..idx]ordf[, idx, with = FALSE]