Reputation: 4376
Take
DT <- CJ(1:2, 2:3)
key.the.DT <- function(data.table, primary.key)
setkey(data.table, primary.key)
key.the.DT(data.table = DT, primary.key = 'V1')
returns
Error in setkeyv(x, cols, verbose = verbose, physical = physical) :
some columns are not in the data.table: primary.key
How can I key a data.table from inside a function?
EDIT: For two or more keys...
DT <- CJ(1:2, 2:3, 4:5)
key.the.DT <- function(data.table, the.keys)
setkeyv(data.table, the.keys)
setkey(DT, 'V3')
key(DT)
# [1] "V3"
key.the.DT(data.table = DT, the.keys = c('V1', 'V2'))
key(DT)
# [1] "V1" "V2"
Upvotes: 3
Views: 557
Reputation: 887501
We can use setkeyv
inside the function
key.the.DT <- function(data.table, primary.key)
setkeyv(data.table, primary.key)
key.the.DT(data.table = DT, primary.key = 'V1')
key(DT)
#[1] "V1"
Upvotes: 4