title: How to apply a function to a subset of columns in r?
body: <p>I am using <code>by</code> to apply a function to <strong>a range columns</strong> of a data frame based on a factor. Everything works perfectly well if I use <code>mean()</code> as the function but if I use <code>median()</code> I get an error of the type <em>"Error in median.default(x) : need numeric data"</em> even if I don't have NAs in the data frame.</p>
  
  <p>The line that works using <code>mean()</code>:</p>
  
  <pre><code>by(iris[,1:3], iris$Species, function(x) mean(x,na.rm=T))
  
  &gt; by(iris[,1:3], iris$Species, function(x) mean(x,na.rm=T))
  iris$Species: setosa
  Sepal.Length  Sepal.Width Petal.Length 
         5.006        3.428        1.462 
  ------------------------------------------------------------ 
  iris$Species: versicolor
  Sepal.Length  Sepal.Width Petal.Length 
         5.936        2.770        4.260 
  ------------------------------------------------------------ 
  iris$Species: virginica
  Sepal.Length  Sepal.Width Petal.Length 
         6.588        2.974        5.552 
  Warning messages:
  1: mean(&lt;data.frame&gt;) is deprecated.
   Use colMeans() or sapply(*, mean) instead. 
  2: mean(&lt;data.frame&gt;) is deprecated.
   Use colMeans() or sapply(*, mean) instead. 
  3: mean(&lt;data.frame&gt;) is deprecated.
   Use colMeans() or sapply(*, mean) instead. 
  </code></pre>
  
  <p>But if I use <code>median()</code> (note the <code>na.rm=T option</code>):</p>
  
  <pre><code>&gt; by(iris[,1:3], iris$Species, function(x) median(x,na.rm=T))
  Error in median.default(x, na.rm = T) : need numeric data
  </code></pre>
  
  <p>However if instead of choosing the range <code>[,1:3]</code> of columns I choose only one of the columns it works:</p>
  
  <pre><code>&gt; by(iris[,1], iris$Species, function(x) median(x,na.rm=T))
  iris$Species: setosa
  [1] 5
  ------------------------------------------------------------ 
  iris$Species: versicolor
  [1] 5.9
  ------------------------------------------------------------ 
  iris$Species: virginica
  [1] 6.5
  </code></pre>
  
  <p>How can I achieve this behaviour while selecting a range of columns?</p>