Looping and finding nearest data points for sub-groups
<p>I'm trying to replicate the work done in the really <a href="https://stackoverflow.com/questions/21977720/r-finding-closest-neighboring-point-and-number-of-neighbors-within-a-given-rad">cool nearest neighbor question</a> but do it for each area in my dataframe rather than the group as a whole.</p>

<p>My data ncbaby (don't ask) looks like this:</p>

<pre><code>     id      printid     areaname latitude longitude
1  7912048 233502729     073    36.06241 -80.44229
2   735253 171241999 Area 12-06 35.54452 -78.75388
3  4325564  85564887 Area 12-04 35.49328 -78.73756
4  4222241  85461255 Area 12-06 35.53621 -78.75553
5 11997754 356053648 Area 12-04 35.49328 -78.73756
6 13444458 536073775 Area 12-06 35.53987 -78.74922
</code></pre>

<p>I'd like to run the function for each areaname. I tried calling split but but the distance function won't call on a list. </p>

<pre><code>splitfile &lt;- split(ncbaby, ncbaby$precinctname)

c &lt;- gDistance(splitfile, byid=TRUE)

Error in (function (classes, fdef, mtable)  : 
unable to find an inherited method for function ‘is.projected’ for signature ‘"list"’
</code></pre>

<p>The closest I've gotten is:</p>

<pre><code>library(sp)
library(rgeos)

uniq &lt;- unique(unlist(ncbaby$areaname))
for (i in 1:length(uniq)){
    data_1 &lt;- subset(ncbaby, areaname == uniq[i])
    sp.mydata &lt;- data_1
    coordinates(sp.mydata) &lt;- ~longitude+latitude
    d &lt;- gDistance(sp.mydata, byid=TRUE)
    min.d &lt;- apply(d, 1, function(x) order(x, decreasing=F)[2])
    newdata &lt;- cbind(data_1, data_1[min.d,], apply(d, 1, function(x) sort(x, decreasing=F)[2]))
    colnames(newdata) &lt;- c(colnames(data_1), 'n.ID',
                          'n.printid', '.Areaname', 'n.latitude', 'n.longitude',
                          'distance')
}
</code></pre>

<p>The problem here is that it ends up kicking out only the last returned value. ideas? I'd be interested/open to modifying the function as well, as it seems it might be more efficient. </p>