Nikita Nikita - 3 months ago 18
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?


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)