3

I have the following data table tb1

persid    date        rating
10000     1/1/2014    A
10000     1/2/2014    B
10001     1/1/2014    A
10001     1/2/2014    B
10002     1/1/2014    A
10002     1/2/2014    B
 .          .         .
 .          .         .
 .          .         .

I set persid as the key by using command:

setkey[tb1, persid]

But when I run the command:

tb1['10000']

it is giving me an error msg:

Error in `[.data.table`(prhistory, "10000") : typeof x.persid (integer) != typeof i.persid (character)

But if I remove the quotation, i.e. just tb1[10000], then it is giving me the value of the 1000th row.

So how can I subset with a key that is an integer in this data table?

I am using package data.table.

Thanks

PMa
  • 1,751
  • 7
  • 22
  • 28

1 Answers1

4

Either of these will work

setkey(tb1,persid)
tb1[J(10000)]
#    persid     date rating
# 1:  10000 1/1/2014      A
# 2:  10000 1/2/2014      B
tb1[persid==10000]
#    persid     date rating
# 1:  10000 1/1/2014      A
# 2:  10000 1/2/2014      B
jlhoward
  • 58,004
  • 7
  • 97
  • 140
  • Thanks, both worked! Just curious, what the `J` did to `10000`? – PMa Apr 14 '14 at 03:56
  • 2
    @PerriMa, it's a shortcut to convert to a `data.table` for `join`. Check [this post](http://stackoverflow.com/questions/22001945/how-is-j-function-implemented-in-the-r-package-data-table/22002174#22002174). – Arun Apr 14 '14 at 12:11