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,