sds
sds

Reputation: 60014

Subsetting columns works on data.frame but not on data.table

I can select a few columns from a data.frame:

> z[c("events","users")]
     events  users
1  26246016 201816
2    942767 158793
3  29211295 137205
4  30797086 124314

but not from a data.table:

> best[c("events","users")]
Starting binary search ...Error in `[.data.table`(best, c("events", "users")) : 
  typeof x.pixel_id (integer) != typeof i.V1 (character)
Calls: [ -> [.data.table

What do I do? Is there a better way than to turn the data.table back into a data.frame?

Upvotes: 1

Views: 284

Answers (2)

Arun
Arun

Reputation: 118799

Column subsetting should be done in j, not in i. Do instead:

DT[, c("x", "y")]

Check this presentation (slide 4) to get an idea of how to read a data.table syntax (more like SQL). That'll help convince you that it makes more sense for providing columns in j - equivalent of SELECT in SQL.

Upvotes: 5

Matt Weller
Matt Weller

Reputation: 2754

Given that you're looking for a data.table back you should use list rather than c in the j part of the call.

z[, list(events,users)]    # first comma is important

Note that you don't need the quotes around the column names.

Upvotes: 6

Related Questions