首页 文章

汇总/汇总每组的多个变量(例如总和,平均值)

提问于
浏览
130

从数据框架中,是否有一种简单的方法可以同时聚合( summeanmax et c)多个变量?

以下是一些示例数据:

library(lubridate)
days = 365*2
date = seq(as.Date("2000-01-01"), length = days, by = "day")
year = year(date)
month = month(date)
x1 = cumsum(rnorm(days, 0.05)) 
x2 = cumsum(rnorm(days, 0.05))
df1 = data.frame(date, year, month, x1, x2)

我想同时按年份和月份汇总 df2 数据框中的 x1x2 变量 . 以下代码聚合 x1 变量,但是是否也可以同时聚合 x2 变量?

### aggregate variables by year month
df2=aggregate(x1 ~ year+month, data=df1, sum, na.rm=TRUE)
head(df2)

任何建议将不胜感激 .

6 回答

  • 175

    这个 year() 函数来自哪里?

    您还可以使用 reshape2 包执行此任务:

    require(reshape2)
    df_melt <- melt(df1, id = c("date", "year", "month"))
    dcast(df_melt, year + month ~ variable, sum)
    #  year month         x1           x2
    1  2000     1  -80.83405 -224.9540159
    2  2000     2 -223.76331 -288.2418017
    3  2000     3 -188.83930 -481.5601913
    4  2000     4 -197.47797 -473.7137420
    5  2000     5 -259.07928 -372.4563522
    
  • 46

    是的,在您的 formula 中,您可以 cbind 要聚合的数字变量:

    aggregate(cbind(x1, x2) ~ year + month, data = df1, sum, na.rm = TRUE)
       year month         x1          x2
    1  2000     1   7.862002   -7.469298
    2  2001     1 276.758209  474.384252
    3  2000     2  13.122369 -128.122613
    ...
    23 2000    12  63.436507  449.794454
    24 2001    12 999.472226  922.726589
    

    请参阅 ?aggregateformula 参数和示例 .

  • 42

    使用 data.table 包,速度快(对于较大的数据集很有用)

    https://github.com/Rdatatable/data.table/wiki

    library(data.table)
    df2 <- setDT(df1)[, lapply(.SD, sum), by=.(year, month), .SDcols=c("x1","x2")]
    setDF(df2) # convert back to dataframe
    

    使用plyr包

    require(plyr)
    df2 <- ddply(df1, c("year", "month"), function(x) colSums(x[c("x1", "x2")]))
    

    使用Hmisc包中的summarize()(虽然我的例子中列 Headers 很乱)

    # need to detach plyr because plyr and Hmisc both have a summarize()
    detach(package:plyr)
    require(Hmisc)
    df2 <- with(df1, summarize( cbind(x1, x2), by=llist(year, month), FUN=colSums))
    
  • 42

    使用 dplyr 包,您可以使用 summarise_allsummarise_atsummarise_if 函数同时聚合多个变量 . 对于示例数据集,您可以按如下方式执行此操作:

    library(dplyr)
    # summarising all non-grouping variables
    df2 <- df1 %>% group_by(year, month) %>% summarise_all(sum)
    
    # summarising a specific set of non-grouping variables
    df2 <- df1 %>% group_by(year, month) %>% summarise_at(vars(x1, x2), sum)
    df2 <- df1 %>% group_by(year, month) %>% summarise_at(vars(-date), sum)
    
    # summarising a specific set of non-grouping variables based on condition (class)
    df2 <- df1 %>% group_by(year, month) %>% summarise_if(is.numeric, sum)
    

    后两种选择的结果:

    year month        x1         x2
       <dbl> <dbl>     <dbl>      <dbl>
    1   2000     1 -73.58134  -92.78595
    2   2000     2 -57.81334 -152.36983
    3   2000     3 122.68758  153.55243
    4   2000     4 450.24980  285.56374
    5   2000     5 678.37867  384.42888
    6   2000     6 792.68696  530.28694
    7   2000     7 908.58795  452.31222
    8   2000     8 710.69928  719.35225
    9   2000     9 725.06079  914.93687
    10  2000    10 770.60304  863.39337
    # ... with 14 more rows
    

    注意:不推荐使用 summarise_each ,而选择 summarise_allsummarise_atsummarise_if .


    my comment above中所述,您还可以使用 reshape2 -package中的 recast 函数:

    library(reshape2)
    recast(df1, year + month ~ variable, sum, id.var = c("date", "year", "month"))
    

    这将给你相同的结果 .

  • 3

    有趣的是,这里没有展示基础R aggregatedata.frame 方法,above使用公式接口,所以为了完整性:

    aggregate(
      x = df1[c("x1", "x2")],
      by = df1[c("year", "month")],
      FUN = sum, na.rm = TRUE
    )
    

    More generic use of aggregate's data.frame method:

    因为我们提供的是

    • data.frame as x

    • a listdata.frame 也是 list )为 by ,如果我们需要以动态方式使用它,这非常有用,例如:使用其他列进行聚合和聚合非常简单

    • 还具有定制的聚合功能

    例如:

    colsToAggregate <- c("x1")
    aggregateBy <- c("year", "month")
    dummyaggfun <- function(v, na.rm = TRUE) {
      c(sum = sum(v, na.rm = na.rm), mean = mean(v, na.rm = na.rm))
    }
    
    aggregate(df1[colsToAggregate], by = df1[aggregateBy], FUN = dummyaggfun)
    
  • 0

    迟到了,但最近又找到了另一种获取汇总统计的方法 .

    library(psych) describe(data)

    将输出:每个变量的平均值,最小值,最大值,标准偏差,n,标准误差,峰度,偏度,中位数和范围 .

相关问题