2
\$\begingroup\$

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.

My answer was:

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.

\$\endgroup\$
5
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.