I am not sure how to loop over each column to replace the NA values with the column mean. When I am trying to replace for one column using the following, it works well.
Column1[is.na(Column1)] <- round(mean(Column1, na.rm = TRUE))
The code for looping over columns is not working:
for(i in 1:ncol(data)){
data[i][is.na(data[i])] <- round(mean(data[i], na.rm = TRUE))
}
the values are not replaced. Can someone please help me with this?
dplyr
'smutate_all
ormutate_at
could be useful here:A relatively simple modification of your code should solve the issue:
Similar to the answer pointed out by @Thomas, This can also be done using
ifelse()
method of R:where, Arguments to
ifelse(TEST, YES , NO)
are:-TEST- logical condition to be checked
YES- executed if the condition is True
NO- else when the condition is False
and
ave(x, ..., FUN = mean)
is method in R used for calculating averages of subsets of x[]To add to the alternatives, using @akrun's sample data, I would do the following:
You could also try:
data