title: How to create conditionally new groups when summarizing group means in R
body: <p>I have data for which I want to summarize group means. I then would like to re-group some of the smaller groups (matching a certain n &lt; x condition) into a group called "others". I found a way to do this. But it feels like there are more efficient solutions out there. I wonder how a data.table approach would solve the problem.</p>
  
  <p>Here is an example using tibble and dyplr.</p>
  
  <pre><code># preps
  library(tibble)
  library(dplyr)
  set.seed(7)
  
  # generate 4 groups with more observations
  tbl_1  &lt;- tibble(group = rep(sample(letters[1:4], 150, TRUE), each = 4),
                   score = sample(0:10, size = 600, replace = TRUE))
  
  # generate 3 groups with less observations
  tbl_2 &lt;- tibble(group = rep(sample(letters[5:7], 50, TRUE), each = 3),
                  score = sample(0:10, size = 150, replace = TRUE)) 
  
  # put them into one data frame
  tbl &lt;- rbind(tbl_1, tbl_2)
  
  # aggregate the mean scores and count the observations for each group
  tbl_agg1 &lt;- tbl %&gt;%
    group_by(group) %&gt;%
    summarize(MeanScore = mean(score),
              n = n())
  </code></pre>
  
  <p>So far so easy.
  Next I want to only show groups with more than 100 observations. All other groups should be merged into one group called "others". </p>
  
  <pre><code># First, calculate summary stats for groups less then n &lt; 100
  tbl_agg2 &lt;- tbl_agg1 %&gt;%
     filter(n&lt;100) %&gt;%
        summarize(MeanScore = weighted.mean(MeanScore, n),
                  sumN = sum(n))
  </code></pre>
  
  <p>Note: There was a mistake in the calculation above which is now corrected (@Frank: thanks for spotting it!)</p>
  
  <pre><code># Second, delete groups less then n &lt; 100 from the aggregate table and add a row containing the summary statistics calculated above instead
  tbl_agg1 &lt;- tbl_agg1 %&gt;%
     filter(n&gt;100) %&gt;%
        add_row(group = "others", MeanScore = tbl_agg2[["MeanScore"]], n = tbl_agg2[["sumN"]])
  </code></pre>
  
  <p>tbl_agg1 basically shows what I want it to show, but I wonder if there is a smoother, more efficient way to do this. At the same time I wonder how a data.table approach would deal with the problem at hand.</p>
  
  <p>I welcome any suggestions.</p>