【问题标题】:get the sum of one column and average of the other with grouping通过分组获得一列的总和和另一列的平均值
【发布时间】:2019-06-19 14:54:56
【问题描述】:

我有一个如下所示的数据框:

    Year Iteration Production Technology
    2015     1     200        Gas
    2015     1     305        Gas
    2016     1     150        Gas
    2016     1     200        Gas
    2015     2     200        Gas 

“技术”列说明了发电厂的类型。因此,对于每年和每次迭代,“技术”列中都可以有多个工厂。

我想汇总数据,以便获得一个年度值、所有迭代的平均值以及针对该特定技术的所有发电厂的总和。

在这个例子中是:

    Year Iteration Production Technology 
    2015 1.5       705        Gas
    2016 1.5       350        Gas

我尝试了各种使用聚合函数的方法,但失败了,因为它还会聚合技术列(将总产量除以发电厂的数量)。

【问题讨论】:

  • 不会是 'Iteration be 1.3 for 2015 的 mean
  • 您能否提供更多具有不同技术的行,并在此基础上更改所需的输出。到目前为止,您的解释有点混乱,我不确定我们是否正确回答了您的问题。

标签: r dataframe aggregate


【解决方案1】:

一个选项是 tidyverse 按“年份”、“技术”分组,获得“迭代”的 mean 和“生产”的 sum

library(tidyverse)
df1 %>% 
     group_by(Year, Technology) %>%
     summarise(Iteration = mean(Iteration),
               Production = sum(Production))
# A tibble: 2 x 4
# Groups:   Year [2]
#   Year Technology Iteration Production
#  <int> <chr>          <dbl>      <int>
#1  2015 Gas             1.33        705
#2  2016 Gas             1           350

数据

df1 <- structure(list(Year = c(2015L, 2015L, 2016L, 2016L, 2015L), Iteration = c(1L, 
1L, 1L, 1L, 2L), Production = c(200L, 305L, 150L, 200L, 200L), 
    Technology = c("Gas", "Gas", "Gas", "Gas", "Gas")), 
    class = "data.frame", row.names = c(NA, 
-5L))

【讨论】:

    【解决方案2】:

    data.table中的另一种方法:

    library(data.table)
    
    dt1[ , list(Iteration=mean(Iteration), 
                Production=sum(Production)), 
                                            by=list(Year,Technology)]
    
    #>    Year Technology Iteration Production
    #> 1: 2015        Gas  1.333333        705
    #> 2: 2016        Gas  1.000000        350
    

    作为我最近对 的痴迷的副作用,这是使用sqldf 包的解决方案:

    library(sqldf)
    
    sqldf("select Year, Technology, 
           avg(Iteration) as AVG_Iteration, sum(Production) as TOT_Production
           from dt1 
           group by Year, Technology", drv="SQLite")
    
    #>   Year Technology AVG_Iteration TOT_Production
    #> 1 2015        Gas      1.333333            705
    #> 2 2016        Gas      1.000000            350
    

    reprex package (v0.3.0) 于 2019 年 6 月 19 日创建

    数据:

    dt1 <- fread(input = "  Year Iteration Production Technology
                            2015     1     200        Gas
                            2015     1     305        Gas
                            2016     1     150        Gas
                            2016     1     200        Gas
                            2015     2     200        Gas ")
    

    【讨论】:

      猜你喜欢
      • 2019-01-03
      • 2017-03-25
      • 2016-06-11
      • 2018-11-22
      • 2012-06-27
      • 1970-01-01
      • 1970-01-01
      • 2021-08-07
      • 1970-01-01
      相关资源
      最近更新 更多