title: How to incorporate this function into another function in R?
body: <p>I have a function (<code>centroid</code>) that calculates the centroids (means) across points. I'm trying to incorporate it into the <code>k_means</code> function instead of using 'mean'. Replacing 'mean' with <code>centroid</code> returns an error: <code>do.call(&quot;cbind&quot;, pointList) : second argument must be a list</code>. My data is in matrix form with multiple columns, so this may be the issue. Can anyone suggest a fix where I can incorporate the <code>centroid</code> function into the <code>k_means</code> function, instead of using 'mean'?</p>
  <pre><code>centroid &lt;- function(pointList) {
    rowMeans(do.call(&quot;cbind&quot;, pointList))
  }
  
  k_means = function(x, centers, distFun) {
    prevClusters = NULL
    prevCenters = NULL
    
    repeat {
      distsToCenters = distFun(x, centers)
      clusters = apply(distsToCenters, 1L, which.min)
      centers = apply(x, 2L, tapply, clusters, mean) # If I replace 'mean' here with 'centroid', error comes
      if (identical(prevClusters, clusters)) break
      
      prevClusters = clusters
      prevCenters = centers
    }
    
    list(clusters = clusters, centers = centers)
  }
  </code></pre>