I have dataset in which multiple(8) variables with same class have NA values. So how do I deal with the all the variables's NA values in just one loop. I have tried with this code, but It didn't work.
sapply(final_data,function(x){
x[is.na(x)]<-mean(x,na.rm=TRUE)
})
It has just returned mean values for each variable present in data.
Please let me know is there any alternative way to handle such all NA values with one time.
df <- data.frame(A = c(1,2,NA,4), B = c(5,NA,3,1), C = c(NA,2,3,NA))
df
#> A B C
#> 1 1 5 NA
#> 2 2 NA 2
#> 3 NA 3 3
#> 4 4 1 NA
df[] <- sapply(df, function(x) ifelse(is.na(x), mean(x, na.rm = TRUE), x))
df
#> A B C
#> 1 1.000000 5 2.5
#> 2 2.000000 3 2.0
#> 3 2.333333 3 3.0
#> 4 4.000000 1 2.5
Created on 2019-04-20 by the reprex package (v0.2.1)
However, I would be cautious about calculating further results after replacing NA with the column mean.
Thank You for your response! It worked, However, that changed my class of dataset into the matrix and then I have changed to data.frame class and did the other calculations.