title: dplyr -Error in UseMethod("group_by_")
body: <p>I need to create a function that has an optional parameter, depending on if the frequencies are given or have to be calculated:
  Example tables:</p>
  
  <p>If they are given:</p>
  
  <pre><code>tbl &lt;- data.frame(
      campoALimp = c('uno', "uno1", "Maria", "Mariana", "María", "Mara"),
      freqAbs = c(2, 5, 2, 6, 7, 6))
  </code></pre>
  
  <p>If not:</p>
  
  <pre><code>tbl1 &lt;- data.frame(campoALimp = tbl[rep(1:nrow(tbl), tbl[ , 2]), 1])
  </code></pre>
  
  <p>My function (part of it) is:</p>
  
  <pre><code>limpio &lt;- function (tabla, campo, campo_conteo){
      tabla &lt;- tabla[nchar(as.character(tabla[, campo])) &gt; 2, ]
  
      if(missing(campo_conteo))
          { print("calcula freq")
          #detach("package:plyr", unload=TRUE) 
          require(dplyr)
          tabla1&lt;-data.frame(tabla %&gt;% 
              group_by_(campo) %&gt;% summarise(frecuencia = n() )) 
      } else {tabla1 &lt;- tabla
      tabla1$frecuencia &lt;- tabla1[, campo_conteo]}
  return(tabla1)
  }
  </code></pre>
  
  <p>First, I have problems with detach (in this case is commented but if I use it it shows error:</p>
  
  <blockquote>
    <p>Error in detach("package:plyr", unload = TRUE) : invalid 'name'
    argument</p>
  </blockquote>
  
  <p>If I run the code for the table with frequencies, I have no problem (it's only copying the original table). </p>
  
  <pre><code>limpio(tbl1, 'campoALimp')
  </code></pre>
  
  <p>But If I run it for the 2nd table:
  I got the following error:</p>
  
  <pre><code>limpio(tbl, 'campoALimp', 'freqAbs')
  Error in UseMethod("group_by_") : 
    no applicable method for 'group_by_' applied to an object of class "factor"
  </code></pre>
  
  <p>I tried writing the detach plyr outside the function and the run the function, and I got the same error.</p>
  
  <p>I tried doing the same outside the function:</p>
  
  <pre><code>tabla &lt;- tbl1
  campo &lt;- 'campoALimp'
  tabla1 &lt;- NULL
  tabla1 &lt;- data.frame(tabla %&gt;% 
              group_by_(campo) %&gt;% summarise(frecuencia = n() )) 
  </code></pre>
  
  <p>And I get the correct result</p>
  
  <pre><code>  campoALimp frequency
         Mara          6
        Maria          2
        María          7
      Mariana          6
          uno          2
         uno1          5
  </code></pre>
  
  <p>Why this is not working inside the function?
  Thanks.</p>