Replace missing values with column mean
A relatively simple modification of your code should solve the issue:
for(i in 1:ncol(data)){
data[is.na(data[,i]), i] <- mean(data[,i], na.rm = TRUE)
}
If DF
is your data frame of numeric columns:
library(zoo)
na.aggregate(DF)
ADDED:
Using only the base of R define a function which does it for one column and then lapply to every column:
NA2mean <- function(x) replace(x, is.na(x), mean(x, na.rm = TRUE))
replace(DF, TRUE, lapply(DF, NA2mean))
The last line could be replaced with the following if it's OK to overwrite the input:
DF[] <- lapply(DF, NA2mean)