Extract a column by reference from a data.table as a vector

Viewed 2661

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.

1 Answers
Related