user3809734
user3809734

Reputation: 193

R data.table setkey on numeric column

Do we really need to add J() to select numeric column?

We can get the result of character column without J().

library(data.table)
DT = data.table(x=rep(c("a","b","c"),each=3), y=c(1,3,6), v=1:9)
setkey(DT,x)  
DT["a"]  
#    x y v
# 1: a 1 1
# 2: a 3 2
# 3: a 6 3

setkey(DT,y)  
DT["1"]  
# Error in `[.data.table`(DT, "1") : 
#  typeof x.y (double) != typeof i.y (character)

# Is it a bug?

DT[J(1)]
#    y x v
# 1: 1 a 1
# 2: 1 b 4
# 3: 1 c 7

Thanks!

Upvotes: 0

Views: 967

Answers (1)

G. Grothendieck
G. Grothendieck

Reputation: 269852

The reason that DT[1] is not the same as DT[J(1)] is that there are TWO different interpretations that we might want:

  1. the first row, DT[1]
  2. all rows for which the key equals 1, DT[J(1)]

The potential ambiguity only exists if the first argument is numeric which is why there are two different notations for the two situations.

In the case of a character key this potential ambiguity does not arise since a character argument could only mean the second case.

Also, DT["1"] is an error in the code of the question since the key in the example is not character and data.table does not perform coercion of types here.

Upvotes: 5

Related Questions