5

Is it possible to select a column of a data.table and get back a vector? In base R, the argument drop=TRUE would do the trick. For example,

library(data.table)
dat <- as.data.table(iris)
dat[,"Species"] # returns data.table
dat[,"Species", drop=TRUE] # same
iris[, "Species", drop=TRUE] # a factor, wanted result

Is there a way to do this with data.table?

EDIT: the dat[,Species] method is fine, however I need a method where I can pass the column name in a variable:

x <- "Species"
dat[,x, drop=TRUE]
3
  • 2
    In newer data.table versions you can just say dat[, Species]. You get a factor here because you started with a factor from the iris data set. (I didn't downvote.) Commented Nov 29, 2019 at 20:24
  • 1
    Try dat[,get(x), drop=TRUE] (not my downvote either) Commented Nov 29, 2019 at 20:36
  • 1
    @Karsten It helps if you start with the real question. Try colnam <- "Species" followed by dat[, ..colnam][[1]]. All this is, methinks, in the data.table FAQ ... Commented Nov 29, 2019 at 20:41

3 Answers 3

8

With data.frame, the default is drop = TRUE and in data.table, it is the opposite while it is done internally. According to ?data.table

drop - Never used by data.table. Do not use. It needs to be here because data.table inherits from data.frame.

In order to get the same behavior, we can use [[ to extract the column by passing a string

identical(dat[["Species"]], iris[, "Species"])
#[1] TRUE

Or

dat$Species

By using [[ or $, it extracts as a vector while also bypass the data.table overhead

Sign up to request clarification or add additional context in comments.

Comments

1

In data.table, if you use column name to select columns, it depends how you write the name.

library(data.table)
dat <- as.data.table(iris)
dat[,"Species"] # returns a data.table
dat[["Species"]] # returns a vector, like selection of list elements.
dat[, Species] # returns a vector, use it like a variable.

To note, if you need a vector with some filters:

dat[petal.Length > 1, Species] # dat[["Species"]] can not use condition in i expression.
dat[petal.Length > 1, `#Species`] # for special name, use `` to quote such as `name@#$%^`

Comments

0

See data.table FAQ #1.1. This comes as a feature since 2006.

Comments

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.