Row-wise mean imputation in R Someone on SO asked how to fill in the NA's with row means. His example code was:


cancer1 &lt;- read.table("cancer.txt", stringsAsFactors = FALSE, quote='', header=TRUE,sep='\t')



Since he didn't provide the data I think we can simulate it with:


cancer1 &lt;- data.frame(a=rep(c(1,2,3,NA),10),b=rep(c(1,2,3,4),10), c=seq(1,40,1))



Just bear in mind that the example data is an arbitrary simulation.

My answer was:

for(i in 1:nrow(cancer1)){
  for(n in 1:ncol(cancer1)){
    if(is.na(cancer1[i,n])){
        cancer1[i,n]  &lt;-  mean(t(cancer1[i,]), na.rm = T)# or  rowMeans(cancer1[i,], na.rm=T)
    }
    }
}


I know that this can be vectorized and otherwise improved, but I'm just not sure how.
You can use rowMeans with indexing.

k &lt;- which(is.na(cancer1), arr.ind=TRUE)
cancer1[k] &lt;- rowMeans(cancer1, na.rm=TRUE)[k[,1]]


Where k is an indices of the rows with NA values.