Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Counting rows that match result of calculation in R

I have a line of code that calculates the maximum value for a number of products

data2019 %>%
  group_by(PRODUCT) %>%
  summarise(max_amt = max(AMOUNT))

I want to then count the number of rows where AMOUNT == max_amt for that particular product, but if I try to wrap it in a count or sum function it gives me the max value for the whole set, and the total number of rows for each product, which isn’t very helpful, especially as the values vary considerably. How can I get it to produce the answer for each specific product?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can do a count on condition by writing your summarize like sum(CONDITION). Like so:

data2019 %>%
  group_by(PRODUCT) %>%
  summarize(max_count = sum(AMOUNT == max(AMOUNT)))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading