-1

I used the Group_by function to give me the total sum of amounts by prod_cnt. But now I want to get the average amount per prod_cnt (average/prod_cnt) by prod_cnt group. When I try to divide by count = n(), it just returns (+) signs. How can I get this to work?

Screenshot

Dan
  • 11,370
  • 4
  • 43
  • 68
  • 1
    Welcome to SO! Could you make your problem reproducible by sharing a sample of your data and the code you're working on so others can help (please do not use `str()`, `head()` or screenshot)? You can use the [`reprex`](https://reprex.tidyverse.org/articles/articles/magic-reprex.html) and [`datapasta`](https://cran.r-project.org/web/packages/datapasta/vignettes/how-to-datapasta.html) packages to assist you with that. See also [Help me Help you](https://speakerdeck.com/jennybc/reprex-help-me-help-you?slide=5) & [How to make a great R reproducible example?](https://stackoverflow.com/q/5963269) – Tung Nov 16 '18 at 17:44

1 Answers1

0
  1. don't nest calls to summarize, just include a singgle call and multiple comma-delimited named arguments.
  2. use n() instead of count=n().

Untested code:

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

In order to not recalculate things (likely not a factor, but just for pedagogy), you can do:

HW_data_File %>%
  group_by(prod_cat) %>%
  summarize(
    Total_Sale = sum(amount),
    count = n()
  ) %>%
  mutate(
    Per_amount = Total_Sale / count
  )
r2evans
  • 141,215
  • 6
  • 77
  • 149