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.

5
  • see stackoverflow.com/a/20043412/1412059 Commented May 20, 2017 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. Commented May 20, 2017 at 18:42
  • Now I found this solution was addressed by @Frank answer at this post, the question was not specific for this particular problem, but his solution solves my problem too. Commented May 20, 2017 at 18:46
  • 1
    That answer explains how the index solution works. Extraction by column name works exactly the same. Commented May 20, 2017 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.) Commented May 20, 2017 at 21:48

1 Answer 1

4

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

is.vector(DT[[col]])
#[1] TRUE
Sign up to request clarification or add additional context in comments.

1 Comment

Now I found this solution was addressed by @Frank answer at this post

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.