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 w
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.
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)