I’d like to ask why the data.table in the example below loses its key when I change the value of a key variable at a certain where subset. And whether it’s necessary.
library(data.table)
example(data.table)
setkey(DT,x) # one key var only
DT[J("a"), x := "z"]
DT
x y v v2 m
1: z 1 13 84 5
2: z 3 13 84 5
3: z 6 13 84 5
4: c 1 7 NA 8
5: c 3 8 NA 8
6: c 6 9 NA 8
7: z 1 42 NA 42
8: z 3 42 NA 42
9: z 6 42 NA 42
so that works just fine. However, I’ve lost my key:
key(DT)
NULL
I guess that by reassigning the key column x above the key is erased. Maybe the key should be remembered, i.e. there should be an implicit setkey(DT,x) to keep x as the key? Thanks!
I’m using version 1.8.6. by the way.
From
setkey‘s help file:When you replace elements in any of the keyed columns, the
data.tableis no longer ordered (or at least can’t be guaranteed to be), so the key is unset to reflect that changed reality.An easy solution is to just immediately reset the key: