1

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.

brad
  • 9,573
  • 12
  • 62
  • 89
  • What's wrong using `table(hangry)` ? – Ronak Shah Apr 29 '19 at 04:24
  • 1
    `interaction` would be my suggestion if a simple table is not going to work for the real example - `table(interaction(hangry))` – thelatemail Apr 29 '19 at 04:25
  • You could also do it by concatenating the two columns. `table(paste(hangry$Hungry, hangry$Angry, sep = "/"))` – MKa Apr 29 '19 at 04:28
  • The main problem with table() is that I didn't know it existed. That gives a really nice result - thanks. The other suggestions with interaction() and paste() give even nicer results. Thanks for being nice to someone trying to learn the basics of a new tool! – brad Apr 29 '19 at 04:40
  • Old related questions just to link things up - https://stackoverflow.com/questions/33816890/finding-count-of-na-values-for-combination-of-columns-in-r/33817157 and also essentially - https://stackoverflow.com/questions/9809166/count-number-of-rows-within-each-group – thelatemail Apr 29 '19 at 04:43

1 Answers1

1

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

library(dplyr)

hangry %>% group_by_all() %>% count()
Omry Atia
  • 2,411
  • 2
  • 14
  • 27