1

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?

Community
  • 1
  • 1
sds
  • 55,681
  • 23
  • 150
  • 247
  • 4
    column subsetting should be done in `j`, not in `i`. `DT[, c("x", "y"), with=FALSE]`. Have a look at the 4th slide [here](http://datatable.r-forge.r-project.org/CologneR_2013.pdf) – Arun Jan 16 '14 at 18:35
  • @Arun: thanks - please turn the comment into an answer so that I can accept it. – sds Jan 16 '14 at 18:42
  • sds, have done. Feel free to turn my comments into answers, if appropriate, for the future. – Arun Jan 16 '14 at 18:58
  • 3
    @sds Please also read the [data.table FAQ](http://datatable.r-forge.r-project.org/datatable-faq.pdf). The first few FAQs cover this. – Matt Dowle Jan 17 '14 at 01:37
  • I will repeat something I have said many times before. Implicity is a bitch. Just like sometimes `mydf[, 1, drop = FALSE` comes mighty handy. – Roman Luštrik Jan 17 '14 at 10:46

2 Answers2

6

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.

Matt Dowle
  • 57,542
  • 22
  • 163
  • 221
Matt Weller
  • 2,604
  • 2
  • 20
  • 30
5

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.

MichaelChirico
  • 32,615
  • 13
  • 106
  • 186
Arun
  • 113,200
  • 24
  • 277
  • 373