本文介绍了如何使用eval向data.table添加列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我有一个数据表的观察和模型是是和否。为了简单起见,我只假设组。我浪费计算一些分类统计,我想控制选择哪一个。我知道如何使用eval,并将其保存在另一个data.table,但我想添加到现有的data.table,因为我每个组只有一行。 首先,我为每个组创建应急表。 DT categorical< 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] 然后定义统计 my_exprs = quote(list(n = a + b + c + d,s =(a + c)/(a + b + c + d),r = (a + b)/(a + b + c + d))) 以下行,它将给我一个新的data.table: statList w = which(names(my_exprs)%in%statList) categorical [,eval(my_exprs [c(1,w)]),by = groupBy] 如何使用:=在这个例子中,将结果添加到我的旧DT,这里称为分类?我做了以下,并得到错误消息: 分类[,`:=`(eval(my_exprs [c )])),by = groupBy] 在`[.data.table`(分类,,`:=`(eval(my_exprs [c(1,w)] )),:在`:=`(col1 = val1,col2 = val2,...)形式中,所有参数必须命名 感谢,解决方案我无法重现您的示例,保留 my_exprs ,但定义 my_newcols = as.call在 ://stackoverflow.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)) 这篇关于如何使用eval向data.table添加列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
09-02 01:54