2

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)") ]
MatthewR
  • 2,660
  • 5
  • 26
  • 37
  • Putting expression in a string is a sign of bad design, it is fine to use it, but one should not put such code in production. See https://stackoverflow.com/a/40164111/2490497 – jangorecki May 06 '20 at 01:27

1 Answers1

1

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
akrun
  • 874,273
  • 37
  • 540
  • 662