Nikita Nikita - 2 months ago 9
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[is.na(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][is.na(data[i])] <- round(mean(data[i], na.rm = TRUE))
}


But the values are not replaced.

Can someone please help me with this?

Answer

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)
}