PMa
PMa

Reputation: 1771

subset data with key in R using `data.table` package

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

Upvotes: 3

Views: 806

Answers (1)

jlhoward
jlhoward

Reputation: 59355

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

Upvotes: 4

Related Questions