R 是否有一个有效的一行程序来为data.table中的每组因子运行函数?

R 是否有一个有效的一行程序来为data.table中的每组因子运行函数?,r,data.table,R,Data.table,我正在尽可能有效地解决这个问题,我不知道我现在得到的是不是最好的选择。你们还有别的选择吗 我得到的输出正是我想要的(实际上,如果每个函数的列名不重复就好了),但我想知道是否能找到更好的方法(在那里我进行for循环)。我会尝试一次性完成,然后保存输出。我相信这与您的需求相符,否则请告诉我:) 好的,我得到了主要的想法,试着用它来做一个简单的函数。SummaryStat我将编辑我的答案作为一个函数。有一种更熟悉的语法可以用于by,它可以采用命名向量(见上文)好的,我用过你的方法,它或多或少适用于我需

我正在尽可能有效地解决这个问题,我不知道我现在得到的是不是最好的选择。你们还有别的选择吗


我得到的输出正是我想要的(实际上,如果每个函数的列名不重复就好了),但我想知道是否能找到更好的方法(在那里我进行for循环)。

我会尝试一次性完成,然后保存输出。我相信这与您的需求相符,否则请告诉我:)


好的,我得到了主要的想法,试着用它来做一个简单的函数。SummaryStat我将编辑我的答案作为一个函数。有一种更熟悉的语法可以用于by,它可以采用命名向量(见上文)好的,我用过你的方法,它或多或少适用于我需要的所有字段,但是如果我想将分位数函数的结果添加到帧中怎么办?
# try converting to long format, and then using the by conditions to get 
# aggregate views
# melt is used to convert wide to long, splitting columns over combinations 
# of the id.vars
tr2 <- melt(tr, id.vars = c("industry", "country"))
# do the aggregations, at (1) industry level, (2) at country level
sol1 <- tr2[, .(N=.N, min=min(value), max=max(value)), by=.(variable, industry)]
sol2 <- tr2[, .(N=.N, min=min(value), max=max(value)), by=.(variable, country)]
# sense check
sol1[]
sol2[]
SummaryStat <- function(table, ids){ 
  table <- melt(table, id.vars = ids)

  output <- lapply(ids, function(index){
    table[, .(N=.N, min=min(value), max=max(value)), by=c("variable", index)] 
  })
  names(output) <- ids
  return(output)
} 

SummaryStat(tr, c("industry", "country"))