在R语言中,当group by变量是字符串时,使用data.table聚合统计信息

在R语言中,当group by变量是字符串时,使用data.table聚合统计信息,r,string,group-by,arguments,data.table,R,String,Group By,Arguments,Data.table,我得到了这个数据。表格集: set.seed(1234) r=100 ref=c("banana","chocolate","apple") ref2=c("florida","california") products=sample(ref,r,TRUE) cities=sample(ref2,r,TRUE) quantity=sample(seq(1:5),100,TRUE) dt=data.table(products,quantity,cities) head(dt,5) prod

我得到了这个数据。表格集:

set.seed(1234)
r=100
ref=c("banana","chocolate","apple")
ref2=c("florida","california")
products=sample(ref,r,TRUE)
cities=sample(ref2,r,TRUE)
quantity=sample(seq(1:5),100,TRUE)
dt=data.table(products,quantity,cities)
head(dt,5)

  products quantity     cities
1:    apple        3    florida
2:   banana        5    florida
3:   banana        3    florida
4:    apple        2 california
5:    apple        5    Florida
我想要一个函数,它以groupby变量的索引作为参数。像这样:

sumfn=function(dt,index){
  var_group=c("products","cities")[index]
  res=dt[,list(Q=sum(quantity)),by=list(var_group)]
  return(res)
}
因此,如果我运行此命令:

count_dt=sumfn(dt,1)
我的输出是:

    products   Q
1: chocolate  72
2:    banana  91
3:     apple 136
但是,当我运行上述命令时,会收到以下错误消息:

Error in `[.data.table`(dt, , list(Q = sum(quantity)), by = list(var_group)) : 
  The items in the 'by' or 'keyby' list are length (1). Each must be same length as rows in x or number of rows returned by i (100).

有人知道怎么解决吗?我被这个问题困扰了一个小时。

删除
by
子句中的
列表
,即

sumfn <- function(dt, index) {
    var_group <- c("products", "cities")[index]
    res <- dt[, list(Q = sum(quantity)), by = var_group]
    return(res)
}

删除
by
子句中的
列表
,即

sumfn <- function(dt, index) {
    var_group <- c("products", "cities")[index]
    res <- dt[, list(Q = sum(quantity)), by = var_group]
    return(res)
}

是什么让你想到应该将
var\u组
包装在一个列表中?你不需要使用一个列表,你想包含一个参数
with=FALSE
res=dt[,list(Q=sum(quantity)),by=var\u组,with=FALSE]
你可能需要
c
而不是
list
或只是
var\u组
<当您与其他变量组合时,可以使用code>c。请在随机创建虚拟数据之前使用
set.seed
,例如,通过
sample
runif
。否则,您无法比较结果。是什么让您想到应该将
var_组
包装在列表中?您不需要使用列表,而是希望包含参数
with=FALSE
res=dt[,list(Q=sum(quantity)),by=var_组,with=FALSE]
您可能需要
c
而不是
list
或只需
var\u组
<当您与其他变量组合时,可以使用code>c。请在随机创建虚拟数据之前使用
set.seed
,例如,通过
sample
runif
。否则你就不能比较结果了。但是实际上,我需要把它包装起来,因为某些原因。这是一个更复杂的script.thks的片段,但实际上出于某些原因,我需要将其包装起来。这是一个更复杂脚本的片段。