3

I would like to extract the column values from a data.table object specifying the column name using a variable. For example:

DT <- data.table(x = c(1, 2), y = c(3, 4), z = c(5, 6))
col <- "z"

then

> is.vector(DT[, col, with = F])
[1] FALSE

because it returns a data.table object instead.

I have tried also: is.vector(DT[, (col), with = F]) and also: is.vector(DT[, ..col]) with the same result. I have tried other possibilities that produce an error.

Using directly the variable name works:

> is.vector(DT[, z])
[1] TRUE

I found this post, that solves it using column position but not using a name by reference:

> is.vector(DT[[3]])
[1] TRUE

I didn't find an explicit reference about this particular case in the data.table documentation. I am sure it is an easy way to do it, but I didn't find how.

Community
  • 1
  • 1
David Leal
  • 6,373
  • 4
  • 29
  • 56
  • see http://stackoverflow.com/a/20043412/1412059 – Roland May 20 '17 at 18:36
  • @Roland this solution is by index position, now I realized that for name reference it also works but it was not mentioned explicitly. – David Leal May 20 '17 at 18:42
  • Now I found this solution was addressed by @Frank answer at this [post](http://stackoverflow.com/questions/16617226/referring-to-data-table-columns-by-names-saved-in-variables?rq=1), the question was not specific for this particular problem, but his solution solves my problem too. – David Leal May 20 '17 at 18:46
  • 1
    That answer explains how the index solution works. Extraction by column name works exactly the same. – Roland May 20 '17 at 18:48
  • The first several questions in the FAQ go over the options here (and the FAQ is considered part of the documentation). Type `vignette("datatable-faq")`. (Btw, the FAQ on the website is out of date, I think.) – Frank May 20 '17 at 21:48

1 Answers1

4

We can use the [[ to extract the column as vector

is.vector(DT[[col]])
#[1] TRUE
akrun
  • 874,273
  • 37
  • 540
  • 662
  • 1
    Now I found this solution was addressed by @Frank answer at this [post](http://stackoverflow.com/questions/16617226/referring-to-data-table-columns-by-names-saved-in-variables?rq=1) – David Leal May 20 '17 at 18:43