120

Possible Duplicate:
Variably selecting/assigning to fields in a data.table

In following example, I am creating a data table having column name ‘x’ and ‘v’

library('data.table')
DT <- data.table(x = c("b","b","b","a","a"), v = rnorm(5))

I can access values of column ‘x’ by :

DT[ , x]
# [1] "b" "b" "b" "a" "a"

But if I want to access by passing through a variable, it doesn’t work

temp <- "x"
DT[ , temp]
# [1] "x"

There would be multiple columns and I will have to select values for only couple of them. These column names I will be provide by passing through a R module.

Never mind, I got it, it should be:

DT[ , get(temp)]
Henrik
  • 65,555
  • 14
  • 143
  • 159
user1631306
  • 4,350
  • 8
  • 39
  • 74

1 Answers1

65

Use the quote() and eval() functions to pass a variable to j. You don't need double-quotes on the column names when you do it this way, because the quote()-ed string will be evaluated inside the DT[]

temp <- quote(x)
DT[ , eval(temp)]
# [1] "b" "b" "b" "a" "a"

With a single column name, the result is a vector. If you want a data.table result, or several columns, use list form

temp <- quote(list(x, v))
DT[ , eval(temp)]
#   x           v
# 1: b  1.52566586
# 2: b  0.66057253
# 3: b -1.29654641
# 4: a -1.71998260
# 5: a  0.03159933
Henrik
  • 65,555
  • 14
  • 143
  • 159
Douglas Clark
  • 2,975
  • 2
  • 17
  • 20
  • 38
    For me with R 3.2.0 this does not work. I have to use get(temp) as pointed out by the thread starter. – Exocom Jun 26 '15 at 11:54
  • 2
    I already have a gazillion column names in a character vector all there with double quotes around them. How do I get rid of the quotes? – Farrel Jun 28 '16 at 00:23
  • 3
    And what happens if you already have about 10 columns names in a list statement but you want to add the other gazillion column names. So for the example above it would be something such as `DT[,list(favoritecolumn1, favoritecolumn2, favoritecolumn3, temp)` – Farrel Jun 28 '16 at 00:32
  • 2
    @exocom ... I had the same issue and used the folllowing answer instead: https://stackoverflow.com/questions/12391950/select-assign-to-data-table-variables-which-names-are-stored-in-a-character-ve – hartmut Jun 27 '17 at 13:31
  • 8
    This works for me: `DT[, colnames, with=FALSE][[colnum]]` – ivan866 Feb 27 '20 at 12:27
  • `get()` function works in both `i` and `j` (R version 3.6.3, data.table version 1.12.8), which is an added benefit. – sgrubsmyon Apr 09 '20 at 17:36