且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用eval向data.table添加列

更新时间:2023-11-30 19:35:28

我无法重现您的示例,保留 my_exprs ,但定义

  my_newcols = as.call在  

://***.com/questions/22595765/data-table-joins-select-all-columns-in-the-i-argument/22596160#22596160> Arun的回答。



或者,您可以在开始时使用:= 构建表达式:

  my_newcols = quote(`:=`(n = a + b + c + d,s = a + c))
pre>

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,

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))