# 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 <- 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 <- 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.

for(i in 1:nrow(cancer1)){
for(n in 1:ncol(cancer1)){
if(is.na(cancer1[i,n])){
cancer1[i,n]  <-  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 <- which(is.na(cancer1), arr.ind=TRUE)
cancer1[k] <- rowMeans(cancer1, na.rm=TRUE)[k[,1]]


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

I know this answer is late. Alternatively, you could use !complete.cases() in place is.na() to retrieve the rows that have NA values. I use rowMeans just like m0nhawk and stored the values in a data.frame . I also swapped the NA column with the values from the data.frame.

cancer1 <- data.frame(a=rep(c(1,2,3,NA),10),b=rep(c(1,2,3,4),10), c=seq(1,40,1))
d<- data.frame(mean=rowMeans(cancer1[!complete.cases(cancer1),], na.rm=TRUE))
cancer1[!complete.cases(cancer1),1]<-d


I hope this helps.