【问题标题】:How can I group a dataframe, then summarize a total number for each group, then divide by the number of items in that group?如何对数据框进行分组,然后汇总每个组的总数,然后除以该组中的项目数?
【发布时间】:2018-11-16 17:41:53
【问题描述】:

我使用 Group_by 函数为我提供了 prod_cnt 的总金额。但现在我想通过 prod_cnt 组获得每个 prod_cnt(平均/prod_cnt)的平均数量。当我尝试除以 count = n() 时,它只返回 (+) 符号。我怎样才能让它工作?

【问题讨论】:

标签: r rstudio


【解决方案1】:
  1. 不要将调用嵌套到summarize,只包含一个调用和多个以逗号分隔的命名参数。
  2. 使用n() 而不是count=n()

未经测试的代码:

library(dplyr)
HW_data_File %>%
  group_by(prod_cat) %>%
  summarize(
    Total_Sale = sum(amount),
    count = n(),
    Per_amount = sum(amount) / n()
  )

为了不重新计算事物(可能不是一个因素,而只是为了教学),你可以这样做:

HW_data_File %>%
  group_by(prod_cat) %>%
  summarize(
    Total_Sale = sum(amount),
    count = n()
  ) %>%
  mutate(
    Per_amount = Total_Sale / count
  )

【讨论】:

  • AaronJ,这能回答你的问题吗?如果有,请accept it;这样做不仅为回答者提供了一些积分,而且还为有类似问题的读者提供了一些关闭。 (如果仍有问题,您可能需要编辑您的问题并提供更多详细信息。)
猜你喜欢
  • 2021-12-29
  • 1970-01-01
  • 2022-08-08
  • 1970-01-01
  • 2018-03-23
  • 2020-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多