title: apply function to grouped rows in dataframe
body: <p>I have created a function that computes a number of biological statistics, such as species range edges. Here is a simplified version of the function: </p>
  
  <pre><code>range_stats &lt;- function(rangedf, lat, lon, weighting, na.rm=T){
    cent_lat &lt;- weighted.mean(x=rangedf[,lat], w=rangedf[,weighting], na.rm=T)
    cent_lon &lt;- weighted.mean(x=rangedf[,lon], w=rangedf[,weighting], na.rm=T)
  out &lt;- data.frame(cent_lat, cent_lon)    
  return(out)
  } 
  </code></pre>
  
  <p>I would like to apply this to a large dataframe where every row is an observation of a species. As such, I want the function to group rows by a specified set of columns, and then computer these statistics for each group. Here is a test dataframe: </p>
  
  <pre><code>LATITUDE &lt;- c(27.91977, 21.29066, 26.06340, 28.38918, 25.97517, 27.96313)
  LONGITUDE &lt;- c(-175.8617, -157.8645, -173.9593, -178.3571, -173.9679, -175.7837)
  BIOMASS &lt;- c(4.3540488, 0.2406332, 0.2406332, 2.1419699, 0.3451426, 1.0946017)
  SPECIES &lt;- c('Abudefduf abdominalis','Abudefduf abdominalis','Abudefduf abdominalis','Chaetodon lunulatus','Chaetodon lunulatus','Chaetodon lunulatus')
  YEAR &lt;- c('2005', '2005', '2014', '2009', '2009', '2015')
  testdf &lt;- data.table(LATITUDE, LONGITUDE, BIOMASS, SPECIES, YEAR)
  </code></pre>
  
  <p>I want to apply this function to every unique combination of species and year to calculate summary statistics, i.e., the following: </p>
  
  <pre><code>testresult &lt;- testdf %&gt;%
    group_by(SPECIES, YEAR) %&gt;%
    range_stats(lat="LATITUDE",lon="LONGITUDE",weighting="BIOMASS",na.rm=T)
  </code></pre>
  
  <p>However, the code above does not work (I get a <code>(list) object cannot be coerced to type 'double'</code> error) and I am not sure how else to approach the problem. </p>