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

Is there a way to do a group by and do a full count as well as a count based on filter in same table?

I have a dataset that looks like this

ID|Filter|
 1     Y
 1     N
 1     Y
 1     Y
 2     N
 2     N
 2     N
 2     Y
 2     Y
 3     N
 3     Y
 3     Y

I would like the final result to look like this. A summary count of total count and also when filter is "Y"

ID|All Count|Filter Yes
 1     4          3
 2     5          2
 3     3          2

If i do like this i only get the full count but I also want the folder as the next column

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

 df<- df %>%
 group_by(ID)%>%
 summarise(`All Count`=n())

>Solution :

df %>% 
  group_by(ID) %>%
  summarise(`All Count` = n(),
            `Count Yes` = sum(Filter == "Y"))

# A tibble: 3 × 3
  ID    `All Count` `Count Yes`
  <chr>       <int>       <int>
1 1               4           3
2 2               5           2
3 3               3           2
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