title: Writing a function in R to group by variable column from a data frame
body: <p>I am trying to write a function that will allow me to produce descriptive statistics by grouping across multiple factors in a data frame. I have spent way too many hours trying to get my function to recognize the by variables I am selecting.</p>
  
  <p>Here is the fake data:</p>
  
  <pre><code>grouping1 &lt;- c("red", "blue", "blue", "green", "red", "blue", "red", "green")                 
  grouping2 &lt;- c("high", "high", "low", "medium", "low", "high", "medium", "high")                  
  value &lt;- c(22,40,72,41,36,16,88,99)
  
  fake_df &lt;- data.frame(grouping1, grouping2, value)
  </code></pre>
  
  <p>Fake code example:</p>
  
  <pre><code>library(dplyr)
  
  by_group_fun &lt;- function(fun.data.in, fun.grouping.factor){
    fake_df2 &lt;- fun.data.in %&gt;%
      group_by(fun.grouping.factor) %&gt;%
      summarize(mean = mean(value), median = median(value))
    fake_df2
  }
  by_group_fun(fake_df, grouping1) 
  by_group_fun(fake_df, grouping2) 
  </code></pre>
  
  <p>This gives me:</p>
  
  <blockquote>
  <pre><code> Error in grouped_df_impl(data, unname(vars), drop) : 
    Column `fun.grouping.factor` is unknown
  </code></pre>
  </blockquote>
  
  <h1>Second try</h1>
  
  <p>I tried to assign the by variable selected in the function to a new variable and carry that forward.</p>
  
  <p>Fake code example (second try):</p>
  
  <pre><code>by_group_fun2 &lt;- function(fun.data.in, fun.grouping.factor){
    fun.data.in$by_var &lt;- fun.data.in$fun.grouping.factor
  
    fake_df2 &lt;- fun.data.in %&gt;%
      group_by(by_var) %&gt;%
      summarize(mean = mean(value), median = median(value))
    fake_df2
  }
  
  by_group_fun2(fake_df, grouping1) 
  by_group_fun2(fake_df, grouping2) 
  </code></pre>
  
  <p>This, the second try, gives me:</p>
  
  <blockquote>
  <pre><code> Error in grouped_df_impl(data, unname(vars), drop) : 
    Column `by_var` is unknown
  </code></pre>
  </blockquote>