title: Passing an argument a column name to mean function inside a custom function
body: <p>I want to perform a mean encoding to a high-cardinality variable using 5-fold cross validation. My code is:</p>
  
  <pre><code>df &lt;- data.frame(sample(c(1,2,3,4,5), 1000, replace=T), sample(c(1,0), 1000, replace=T))
  colnames(df) &lt;- c("var", "target")
  
  encode &lt;- function(df, target_var, column_var){
  
  set.seed(520)
  df$group &lt;- as.factor(sample(c(1,2,3,4,5), nrow(df), replace=T, prob=c(0.2,0.2,0.2,0.2,0.2)))
  
  var.enc &lt;- df %&gt;% 
                 select_("group", column_var, target_var) %&gt;% 
                 group_by_("group", column_var) %&gt;% 
                 mutate(var_encoded = mean(target_var)) %&gt;% 
                 ungroup() %&gt;% 
                 select_(column_var, "var_encoded") %&gt;% 
                 distinct() %&gt;% 
                 group_by_(column_var) %&gt;% 
                 mutate(var.enc = mean(var_encoded)) %&gt;% 
                 distinct()
  
  return(var.enc)
  }
  
  encoding &lt;- encode(df = df, column_var = "var", target_var = "target")
  </code></pre>
  
  <p>When I run the code above I got an warning:</p>
  
  <blockquote>
    <p>In mean.default(target_var) : argument is not numeric or logical: returning NA</p>
  </blockquote>
  
  <p>So, how can I pass the argument correctly to <strong>mean</strong>  inside my function? I have tried to use <strong>as.name()</strong> but does not work either. Also, I have used <strong>mean(df[[target_var]])</strong>, but this way the <strong>group_by</strong> is not working and I am getting the global mean as a result.</p>
  
  <p>EDIT: I have added a reproducible example.</p>