通过作为参数传递的一组列聚合数据帧

时间:2018-06-03 11:50:52

标签: r data.table multiple-columns aggregation

我有一个数据框,其中包含一天中不同时间的人的功能集。我想将它聚合不同的持续时间,即1小时,2小时等等。我写了这个函数如下。

 library(data.table)

 getAggregate <- function(comb,limb) {
      comb[Limb == as.character(limb),
      c(fb(BC),
      structure(lapply(.SD,mean),names=meanFeatures),
      structure(lapply(.SD,ivar),names=varFeatures)
      )
     ,by=.(Person,hour(Date),yday(Date),wday(Date))
     ,.SDcols = sigfeats]
 }

我只想将“Person,hour(Date),yday(Date),wday(Date)”作为函数的参数传递给“limb”,以便它可以使用这四个值(或任何其他值)进行聚合这些论点不同。)

1 个答案:

答案 0 :(得分:0)

也许这会像这样......

library(lubridate)
library(data.table)

getAggregate <- function(comb, limb, byList) {
    comb$Hour <- hour(comb$Date)
    comb$YDay <- yday(comb$Date)
    comb$WDay <- wday(comb$Date)
    comb$Minute <- minute(Date)

    comb[Limb == as.character(limb),
         c(
             fb(BC),
             structure(lapply(.SD, mean), names = meanFeatures),
             structure(lapply(.SD, ivar), names = varFeatures)
         )
         , by = byList
         , .SDcols = sigfeats]
}

...你会像这样调用函数......

getAggregate(comb, limb, byList = c("Person", "Hour", "YDay", "WDay", "Minute"))