How to impute missing values with row mean in R

守給你的承諾、 提交于 2019-12-01 21:24:53

问题


From a large data frame, I have extracted a row of numeric data and saved as a vector. Some of the values are missing and marked as NA. I want to impute the missing values with row mean.

Thanks


回答1:


Let x be your vector:

x <- c(NA,0,2,0,2,NA,NA,NA,0,2)
ifelse(is.na(x), mean(x, na.rm = TRUE), x)
# [1] 1 0 2 0 2 1 1 1 0 2

Or if you don't care for the original vector, you can modify it directly:

x[is.na(x)] <- mean(x, na.rm = TRUE)



回答2:


Use this:

filter <- is.na(myVec)

myVec[filter] <- colMeans(myDF[,filter], na.rm=TRUE)

Where myVec is your vector and myDF is your data.frame.



来源:https://stackoverflow.com/questions/17203955/how-to-impute-missing-values-with-row-mean-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!