Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace NA values by row means

Tags:

r

I want to replace my NA values from a matrix acquired by :

read.table(…)

Those values should be the mean of the corresponding row.

I.e, the following row of the table :

1 2 1 NA 2 1 1 2

would become

1 2 1 1.43 2 1 2

Thank you.

like image 312
Delphine Avatar asked Aug 02 '11 20:08

Delphine


People also ask

How do I remove rows containing Na?

To remove all rows having NA, we can use na. omit function. For Example, if we have a data frame called df that contains some NA values then we can remove all rows that contains at least one NA by using the command na. omit(df).

Which function is used to remove rows with Na?

By using na. omit() , complete. cases() , rowSums() , and drop_na() methods you can remove rows that contain NA ( missing values) from R data frame.


1 Answers

Here's some sample data.

m <- matrix(1:16, nrow=4)
m[c(1,4,6,11,16)] <- NA

And here's how I'd fill in missings with the row means.

k <- which(is.na(m), arr.ind=TRUE)
m[k] <- rowMeans(m, na.rm=TRUE)[k[,1]]

Your data will be in a data.frame; you'll have to convert to a matrix first using as.matrix. You may or may not want to leave it in that format; to convert back use as.data.frame.

like image 160
Aaron left Stack Overflow Avatar answered Oct 14 '22 05:10

Aaron left Stack Overflow