Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
451 views
in Technique[技术] by (71.8m points)

r - Replace NA values by row means

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...