rtapply

How to make a tapply style structure containing the N of multiple groups?


Probably very simple but I'm stuck right now: The following code basically returns a list of the Var1 means grouped by Var2 (Group1's mean: 5, Group2's mean: 7, Group3's mean: 4) that can be referred to by Mean_group[GroupX] How would I create a similar structure just showing how many cases there are in each group so I can access the N of each group like this: N_of_each_group <- N of cases belonging to each group N_of_each_group[GroupX]?

data <- data_frame(group = c("A", "B", "C", "A", "B", "B", "B"),values = c(1,2,5,4,6,3,4))
Mean_group <- tapply(as.numeric(values, group, mean, na.rm=TRUE)

It's meant for a Shiny app and the N_of_each_group should be added into a text always matching the group the given user is part of. So if there are 10 people in group 1 and 15 people in group 2 user A from group 1 is supposed to see a text saying "There were 10 people in your group" and user B from group 2 sees a text that reads "There were 15 people in your group".


Solution

  • Dplyr excels in this:

    library(dplyr)
    
    data %>% group_by(group) %>% summarise(mean_group=mean(values, na.rm=TRUE), n_group=n())
    
    # A tibble: 3 x 3
      group mean_group n_group
      <chr>      <dbl>   <int>
    1 A           2.5        2
    2 B           3.75       4
    3 C           5          1