Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

data.table: using setkey with a column name variable

Tags:

I have a variable name saved into the string variable which_id.

W is a data.table. How do I call setkey on W with which_id ?

This is what I've tried

 > eval( paste( 'setkey(W,' , which_id , ')' ) )
[1] "setkey(W, customer_id_A )"

But a call to tables() shows that the customer_id_A key didn't take.

 > evalq( paste( 'setkey(W,' , which_id , ')' ) )
[1] "setkey(W, customer_id_A )"

customer_id_A key still didn't take.

 > setkeyv( W , cols=which_id )

and

 > setkeyv( W , cols=c( which_id ) )

--> same thing, customer_id_A key isn't there.

Any pointers?

like image 907
user2105469 Avatar asked May 02 '13 20:05

user2105469


People also ask

What does setkey do in R?

Description. setkey sorts a data. table and marks it as sorted with an attribute sorted . The sorted columns are the key.

Which function is used to assign a key in data table?

setkey() sorts a data. table and marks it as sorted (with an attribute sorted ). The sorted columns are the key. The key can be any columns in any order.


1 Answers

setkeyv should work. Here is a reproducible example:

library(data.table)
W <- data.table(customer_id_A = 1:2)
which_id <- "customer_id_A"
setkeyv(W, which_id)
tables()
##      NAME NROW MB COLS          KEY          
## [1,] W       2 1  customer_id_A customer_id_A
## Total: 1MB
like image 70
G. Grothendieck Avatar answered Sep 25 '22 08:09

G. Grothendieck