【问题标题】:Creating a row that aggregates the data for that day创建一个聚合当天数据的行
【发布时间】:2022-07-05 23:46:50
【问题描述】:

我有以下模式的数据框:

Date     Item            Purchased
01/01/08 Fruit              48
01/01/08 Confectionary      42
01/01/08 Appliance          11
01/06/08 Confectionary      16
01/06/08 Fruit              19
01/06/08 Appliance          50

我想做的是按日期汇总当天售出的商品总数,作为“商品”列下的一行,可能名称为“总体”或其他名称。因此 01/01/08 将有 4 行包含该日期,其中一行标题为“Overall”,在“Purchased”列中带有“101”。 感谢您提供任何帮助/建议。

【问题讨论】:

    标签: r dataframe


    【解决方案1】:

    我们可以使用

    library(dplyr)
    library(janitor)
    df1 %>%
        group_by(Date) %>%
        group_modify(~ adorn_totals(.x, name = "Overall")) %>%
        ungroup
    

    -输出

    # A tibble: 8 × 3
      Date     Item          Purchased
      <chr>    <chr>             <int>
    1 01/01/08 Fruit                48
    2 01/01/08 Confectionary        42
    3 01/01/08 Appliance            11
    4 01/01/08 Overall             101
    5 01/06/08 Confectionary        16
    6 01/06/08 Fruit                19
    7 01/06/08 Appliance            50
    8 01/06/08 Overall              85
    

    数据

    df1 <- structure(list(Date = c("01/01/08", "01/01/08", "01/01/08", "01/06/08", 
    "01/06/08", "01/06/08"), Item = c("Fruit", "Confectionary", "Appliance", 
    "Confectionary", "Fruit", "Appliance"), Purchased = c(48L, 42L, 
    11L, 16L, 19L, 50L)), class = "data.frame", row.names = c(NA, 
    -6L))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-19
      • 2020-01-20
      • 2020-03-09
      • 1970-01-01
      • 2015-01-08
      • 2017-08-25
      • 1970-01-01
      相关资源
      最近更新 更多