1

I have a data table of observation and model of being yes and no. For simplicity I have assumed only to groups. I wast to calculate some categorical statistics which I want to have control over which one to be chosen. I know how to do it using eval and save it in another data.table but I want to add to the existing data.table as I have only one row for each group. Could anyone help me?

First I create the contingency table for each group.

 DT  <- data.table::data.table(obs = rep(c("yes","no"), 5), mod = c(rep("yes",5), rep("no", 5)), groupBy = c(1,1,1,1,1,2,1,1,2,1))
categorical <- DT[, .(a = sum(obs == category[1] & mod == category[1]),
                  b = sum(obs == category[2] & mod == category[1]),
                  c = sum(obs == category[1] & mod == category[2]),
                  d = sum(obs == category[2] & mod == category[2])), by = groupBy]

Then define the statistics

my_exprs = quote(list(
 n    =  a+b+c+d,
 s    = (a+c)/(a+b+c+d),
 r    = (a+b)/(a+b+c+d))) 

If i use the following lines, it will give me a new data.table:

statList <- c("n","s")
w = which(names(my_exprs) %in% statList)
categorical[, eval(my_exprs[c(1,w)]), by = groupBy]

How to use := in this example to add the results to my old DT, here called categorical?! I did the following and got error message:

categorical[, `:=`(eval(my_exprs[c(1,w)])), by = groupBy]


Error in `[.data.table`(categorical, , `:=`(eval(my_exprs[c(1, w)])),  : 
 In `:=`(col1=val1, col2=val2, ...) form, all arguments must be named.

Thanks,

newbie
  • 757
  • 1
  • 9
  • 19
  • 1
    Does writing `my_newcols = quote(\`:=\`(n = a+b+c+d, s = a+c))` and `eval`ing that work? – Frank Feb 24 '16 at 22:02
  • It might also work to keep your `my_exprs`, but define `my_newcols = as.call(c(quote(\`:=\`), my_exprs))` as in Arun's answer: http://stackoverflow.com/a/22596160/1191259 ..? – Frank Feb 24 '16 at 22:04
  • 1
    thanks @Frank I tried your first suggestion. It works! – newbie Feb 24 '16 at 22:07
  • @Frank please put it as answer so the question can be resolved – jangorecki Mar 01 '16 at 18:52
  • @jan Good idea, but now that I've tried, I realize that the OP's example is not reproducible, calling for some `category` var that doesn't exist. – Frank Mar 01 '16 at 18:56
  • @newbie Do you want to update your question so the example works so an answer can be posted? – Frank Mar 01 '16 at 18:57
  • @Frank if you comment already solved OP question I think it can be safely posted, no all Q&A are reproducible anyway. – jangorecki Mar 01 '16 at 19:09

1 Answers1

0

I cannot reproduce your example, but it might work to keep your my_exprs, but define

my_newcols = as.call(c(quote(`:=`), my_exprs))

as in Arun's answer.

Alternately, you could just construct the expression with a := at the start:

my_newcols = quote(`:=`(n = a+b+c+d, s = a+c))
Community
  • 1
  • 1
Frank
  • 66,179
  • 8
  • 96
  • 180