本文介绍了一个简单的可重现示例,它在R中的自定义函数中将参数传递给data.table的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经搜索了这个答案几个小时了。很多人都问过类似的问题,但是我没有找到一个简单的问题或一个简单的答案。这是我的方法:

I have been googling this answer for a few hours. A lot of people have asked similar questions, but I did not find either a simple enough question or a straightforward answer. Here is my approach:

假设我想在 data.table 中进行一个简单的分组: p>

Assume that I want to do a simple group by in data.table:

library(data.table)
mtcars = data.table(mtcars)
mtcars[,sum(mpg), gear]

# Here are the results
#   gear    V1
#1:    4 294.4
#2:    3 241.6
#3:    5 106.9

但是,如果我使用自定义函数执行此操作:

However, if I use a self-defined function to do this:

zz = function(data, var, group){
  return(data[,sum(var), group])
}
zz(mtcars, mpg, gear)

我收到一条错误消息:

我尝试过替代 eval quote 和其他解决方案,但它们都不起作用。我想知道是否有人可以对此提供更直接的解决方案和解释。

I've tried substitute, eval, quote, and other solutions, but none of them works. I wonder if anyone could give a more straightforward solution and explanation to this.

谢谢你,万圣节快乐!

推荐答案

如果我们使用不带引号的参数,请使用替换 eval uate

If we are using unquoted arguments, substitute and evaluate

zz <- function(data, var, group){
 var <- substitute(var)
 group <- substitute(group)
 setnames(data[, sum(eval(var)), by = group],
        c(deparse(group), deparse(var)))[]
 # or use
 #  setnames(data[, sum(eval(var)), by = c(deparse(group))], 2, deparse(var))[]

}
zz(mtcars, mpg, gear)
#   gear   mpg
#1:    4 294.4
#2:    3 241.6
#3:    5 106.9

这篇关于一个简单的可重现示例,它在R中的自定义函数中将参数传递给data.table的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 18:04