How to impute missing values with row mean in R

心已入冬 提交于 2019-12-01 21:22:59

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)
Ferdinand.kraft

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.

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