Aliases: setkey setkeyv key haskey setindex setindexv indices
Keywords: data
### ** Examples # Type 'example(setkey)' to run these at the prompt and browse output DT = data.table(A=5:1,B=letters[5:1]) DT # before
A B 1: 5 e 2: 4 d 3: 3 c 4: 2 b 5: 1 a
setkey(DT,B) # re-orders table and marks it sorted. DT # after
A B 1: 1 a 2: 2 b 3: 3 c 4: 4 d 5: 5 e
tables() # KEY column reports the key'd columns
NAME NROW NCOL MB COLS KEY 1: DT 5 2 0 A,B B Total: 0MB
key(DT)
[1] "B"
keycols = c("A","B") setkeyv(DT,keycols) DT = data.table(A=5:1,B=letters[5:1]) DT2 = DT # does not copy setkey(DT2,B) # does not copy-on-write to DT2 identical(DT,DT2) # TRUE. DT and DT2 are two names for the same keyed table
[1] TRUE
DT = data.table(A=5:1,B=letters[5:1]) DT2 = copy(DT) # explicit copy() needed to copy a data.table setkey(DT2,B) # now just changes DT2 identical(DT,DT2) # FALSE. DT and DT2 are now different tables
[1] FALSE
DT = data.table(A=5:1,B=letters[5:1]) setindex(DT) # set indices setindex(DT, A) setindex(DT, B) indices(DT) # get indices single vector
[1] "A__B" "A" "B"
indices(DT, vectors = TRUE) # get indices list
[[1]] [1] "A" "B" [[2]] [1] "A" [[3]] [1] "B"