使用data.table自定义函数在R中进行分组时,无法识别group参数。

huangapple go评论72阅读模式
英文:

Customize function in R using using data.table to group by doesn't recognize group argument

问题

I'm simply trying to create a function to sum by group. But, it seems the function never finds 'my_group' argument. The solution needs to be inside a function. 'data.table' and 'tidyverse' options do work outside the function.

What am I missing here?

data=data.table(
group= c('a','b','b','c','c','c'),
value=1:6
)

sum_value_by_group<-function(dt, val, my_group) {
  dt[,group_value:= sum(val), by = my_group]
  return(dt)
}

sum_value_by_group(data, value, group)

Getting this error:
Error in eval(bysub, x, parent.frame()) : object 'group' not found

英文:

I'm simply trying to create a function to sum by group. But, it seems the function never finds 'my_group' argument. The solution needs to be inside a function. 'data.table' and 'tidyverse' options do work outside the function.

What am I missing here?

data=data.table(
group= c(&#39;a&#39;,&#39;b&#39;,&#39;b&#39;,&#39;c&#39;,&#39;c&#39;,&#39;c&#39;),
value=1:6
)

sum_value_by_group&lt;-function(dt, val, my_group) {
  dt[,group_value:= sum(val), by = my_group]
  return(dt)
}

sum_value_by_group(data, value, group)

Getting this error:
Error in eval(bysub, x, parent.frame()) : object 'group' not found

答案1

得分: 2

以下是您要翻译的代码部分:

library(data.table)

sum_value_by_group <- function(dt, val, my_group) {
  dt[, .(group_value = sum(get(val))), by = list(group = get(my_group))]
}
sum_value_by_group(data, 'value', 'group')

#   group group_value
#1:     a           1
#2:     b           5
#3:     c          15

请注意,我只提供了代码的翻译部分。

英文:

One option is to use get and pass the column names as strings.

library(data.table)

sum_value_by_group&lt;-function(dt, val, my_group) {
  dt[, .(group_value = sum(get(val))), by = list(group = get(my_group))]
}
sum_value_by_group(data, &#39;value&#39;, &#39;group&#39;)

#   group group_value
#1:     a           1
#2:     b           5
#3:     c          15

huangapple
  • 本文由 发表于 2023年4月6日 21:45:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/75950269.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定