-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

Lyngbakr
  • 10,426
  • 3
  • 35
  • 61
  • 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
  • 108,754
  • 5
  • 72
  • 122
  • AaronJ, does this answer your question? If so, please [accept it](https://stackoverflow.com/help/someone-answers); doing so not only provides a little perk to the answerer with some points, but also provides some closure for readers with similar questions. (If there are still issues, you will likely need to edit your question with further details.) – r2evans Dec 06 '18 at 21:13