Nikita Nikita - 1 year ago 69
R Question

Replacing Missing Values In R with column mean

I am new to R and I am not sure how loop over columns 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[] <- round(mean(Column1, na.rm = TRUE))

But the code for looping over columns is not working

for(i in 1:ncol(data)){
data[i][[i])] <- round(mean(data[i], na.rm = TRUE))

But the values are not replaced.

Can someone please help me with this?

Answer Source

A relatively simple modification of your code should solve the issue:

for(i in 1:ncol(data)){
  data[[,i]), i] <- mean(data[,i], na.rm = TRUE)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download