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?

6
  • Your indexing works well for iris[, idx] Commented Mar 22, 2021 at 17:24
  • Are you sure you have run idx <- 1:3 first? It should work. Commented Mar 22, 2021 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. Commented Mar 22, 2021 at 17:28
  • Now I read... why should I use the double dot? Commented Mar 22, 2021 at 17:29
  • If it is data.table. you need df[, ..idx] or df[, idx, with = FALSE] Commented Mar 22, 2021 at 17:44

1 Answer 1

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]
Sign up to request clarification or add additional context in comments.

2 Comments

You know of any such function support natively by R?
@user1535147 if you are using base R, then df[idx] would work where df is a data.frame

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.