title: R-Hmisc impute by cluster result
body: <p>I want to impute a variable x3 by the its mean corresponding to each cluster calculated considering other 2 variables X1 and X2. 
  I know that you can pass a function to impute from Hmisc package, like "mean" and it does the work. So I would like to pass a function that does all the following.</p>
  
  <p>I use to write the code to do so:</p>
  
  <pre><code>df1 &lt;- data.frame(x1=runif(1000,0,100),
                    x2=runif(1000,0,100),
                    x3=c(runif(900,0,100),rep(NA,100)))
  </code></pre>
  
  <p>I want to pass a function that does all of this:</p>
  
  <pre><code>clust&lt;-kmeans(df1[,-grep('x3', colnames(df1))], 3)
  df1$clust&lt;-clust$cluster
  
  library(plyr)
  cc&lt;-ddply(df1, 'clust',summarise, mean=mean(x3, na.rm=TRUE))
  
  df2&lt;-merge(df1,cc, by='clust')
  df2$x3imputed2&lt;-ifelse(is.na(df2$x3),df2$mean, df2$x3)
  </code></pre>
  
  <p>Is there a way to pass all this code as a function and use it in Hmisc? (I had a problem with ddply introducing x3 as a variable).</p>
  
  <p>Something like the following:</p>
  
  <pre><code>ff&lt;-function(i) {
  clust&lt;-kmeans(df1[,-grep(i, colnames(df1))], 3)
  df1$clust&lt;-clust$cluster
  cc&lt;-aggregate(df1[,i], by=list(clust=df1$clust), "mean", na.rm=TRUE)
  df2&lt;-merge(df1,cc, by='clust')
  df2$x3imputed2&lt;-ifelse(is.na(df2[, i]),df2$x, df2[,i])
  }
  
  
  f1$imputedx3&lt;-with(df1, impute(x3,ff))
  </code></pre>
  
  <p>But I get an error:</p>
  
  <blockquote>
    <p>empty cluster: try a better set of initial centers</p>
  </blockquote>
  
  <p>And when I replace it by x3 I don't get the same error.</p>