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.
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).
By using na. omit() , complete. cases() , rowSums() , and drop_na() methods you can remove rows that contain NA ( missing values) from R data frame.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With