【问题标题】:R sum of values ​in columns for selected rowsR 选定行的列中值的总和
【发布时间】:2019-12-01 00:08:17
【问题描述】:

我有以下数据集:

         Mark    Model      Sold
1       Skoda  Octavia     21125
2       Skoda    Fabia     19679
3        Opel    Astra     15282
4  Volkswagen     Golf     14190
5      Toyota    Yaris     14032
6      Toyota    Auris     12073
7        Ford    Focus     11126

我需要一个公式来汇总每个品牌的销售数量,以获得如下所示的结果:

         Mark   Total Sold
1       Skoda        40804
2        Opel        15282
3  Volkswagen        14190
4      Toyota        26105
5        Ford        11126

谁能帮我解决这个问题?

【问题讨论】:

    标签: r dplyr sum


    【解决方案1】:

    我们可以按总和使用一个组。在base R 中,这可以通过aggregate 完成

    aggregate(Sold ~ Mark, df1, sum)
    

    或者dplyr

    library(dplyr)
    df1 %>%
       group_by(Mark) %>%
       summarise(Total = sum(Sold))
    # A tibble: 5 x 2
    #  Mark       Total
    #  <chr>      <int>
    #1 Ford       11126
    #2 Opel       15282
    #3 Skoda      40804
    #4 Toyota     26105
    #5 Volkswagen 14190
    

    数据

    df1 <- structure(list(Mark = c("Skoda", "Skoda", "Opel", "Volkswagen", 
    "Toyota", "Toyota", "Ford"), Model = c("Octavia", "Fabia", "Astra", 
    "Golf", "Yaris", "Auris", "Focus"), Sold = c(21125L, 19679L, 
    15282L, 14190L, 14032L, 12073L, 11126L)), 
    class = "data.frame", row.names = c("1", 
    "2", "3", "4", "5", "6", "7"))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-08
      • 1970-01-01
      • 1970-01-01
      • 2017-08-05
      • 2018-03-14
      • 2016-07-30
      相关资源
      最近更新 更多