英文:
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('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
答案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<-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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论