brad
brad

Reputation: 9773

How do I get a summary of 2 columns of yes/no data in R?

Let's say I have a data frame created like so;

> hangry <- data.frame("Hungry" = c("Yes", "Yes", "No", "Yes", "No", "Yes"), "Angry" = c("No", "Yes", "Yes", "No", "No", "Yes"))
> hangry
  Hungry Angry
1    Yes    No
2    Yes   Yes
3     No   Yes
4    Yes    No
5     No    No
6    Yes   Yes

It's easy to get a summary of an individual column like so;

> summary(hangry$Hungry)
 No Yes 
  2   4 

But how would I go about creating a summary of both columns to get counts of each combination. eg something like this;

> summary(hangry$Hungry combined_with hangry$Angry) #yes I know this is a ridiculous simplification
Yes/Yes  Yes/No  No/Yes  No/No
      2       2       1      1

I presume I will need more complicated code that will not give me such a nicely formatted summary. I also presume that there are many ways of achieving what I want. I am fairly new to R though and have become stuck on this.

Upvotes: 1

Views: 1663

Answers (1)

Omry Atia
Omry Atia

Reputation: 2443

dplyr's aggregation functions are very useful for these kinds of summaries:

library(dplyr)

hangry %>% group_by_all() %>% count()

Upvotes: 1

Related Questions