Ina
Ina

Reputation: 4470

Retrieving specific values from subsetting a data.table

I have a data.table in R thus:

my.dt <- data.table(x=seq(1:5),y=(c(TRUE, TRUE, FALSE, FALSE, FALSE)))

I want to extract a single value, or a vector of values from this:

boolean.vector <- my.dt[x<4,"y",with=FALSE]
boolean.value <- my.dt[x<2,"y",with=FALSE]

However, these return values are still of class data.table. As such, I cannot, for example, do the following:

> if(boolean.value) { print("Hello") }
Erro em if (boolean.value) { : argumento não é interpretável como lógico
# (Error in if (boolean.value) { : argument cannot be interpreted as logical)

How can I retrieve the raw values so I can use them in this manner?

Upvotes: 1

Views: 169

Answers (2)

Matt Dowle
Matt Dowle

Reputation: 59612

Instead of

my.dt[1:3,"y",with=FALSE]

I would just do one of:

my.dt$y[1:3]
my.dt[["y"]][1:3]
my.dt[x<2, "y"][[1L]]
my.dt[1:3, get(y)]
my.dt[1:3, eval(as.name(y))]

In base R [[ doesn't copy the vector (it's copy-on-change), so this is very efficient and there isn't any need to use data.table syntax for this.

Upvotes: 3

Sven Hohenstein
Sven Hohenstein

Reputation: 81743

You could use the unlist function to transform the output to a boolean vector:

unlist(boolean.value)
   y 
TRUE 

unlist(boolean.vector)
   y1    y2    y3 
 TRUE  TRUE FALSE 

Upvotes: 2

Related Questions