MatthewR
MatthewR

Reputation: 2770

How to put a string into the keyby parameter in data.table

I know that I can do this,

x<- data.table( mtcars )
x[ , .N , by = as.numeric( gear==4 & carb==4) ]

But I don't know how to do it with character strings. If I was using a single variable name, I could use get() and that would work

x[ , .N , by = get( "as.numeric( gear==4 & carb==4)") ]

Upvotes: 2

Views: 195

Answers (1)

akrun
akrun

Reputation: 887501

Easiest is eval(parse

library(data.table)
x[ , .N , by = .(grp = eval(parse(text = "as.numeric( gear==4 & carb==4)") ))]
#   grp  N
#1:   1  4
#2:   0 28

Upvotes: 1

Related Questions