title: R: aggregate based on factor or numeric
body: <p>I'm trying to aggregate some data that is both numeric and factor variables.  If the variable is numeric I'd like the mean.  If it's a factor I'd like the most frequently occurring value.  I've written the following function but am not getting the output I'd like:</p>
  
  <pre><code>meanOrMostFreq &lt;- function(x){
      if(class(x) == 'factor'){
      tbl &lt;- as.data.frame(table(x))
      tbl$Var1 &lt;- as.character(tbl$Var1)
      return(tbl[tbl$Freq == max(tbl$Freq),'Var1'][1])
      }
      if(class(x) == 'numeric'){
      meanX &lt;- mean(x, na.rm = TRUE)
      return(meanX)
      }
  }
  </code></pre>
  
  <p>Here's how I'm using it:</p>
  
  <pre><code>df1 &lt;- iris[1:148,]
  df1$letter1 &lt;- as.factor(rep(letters[1:4], 37))
  
  momf &lt;- aggregate(.~ Species, df1, FUN = function(x) meanOrMostFreq(x))
  </code></pre>
  
  <p>And the results:</p>
  
  <pre><code>&gt; momf
       Species Sepal.Length Sepal.Width Petal.Length Petal.Width letter1
  1     setosa     5.006000    3.428000     1.462000       0.246    2.46
  2 versicolor     5.936000    2.770000     4.260000       1.326    2.54
  3  virginica     6.610417    2.964583     5.564583       2.025    2.50
  </code></pre>
  
  <p>I'm hoping to get an actual letter in the last column instead of a number.  Any suggestions on what I'm doing wrong?</p>