-1

![1]: https://i.stack.imgur.com/CAA6g.png

So I have the following data frame (df) in which I have columns with some NA´s values. For the purpose of my project I really don't want to have any NA values. Moreover I need to replace all these NA values for the mean of each column variable.

Many Thanks

AdrianGI
  • 39
  • 4
  • you may want to check this link: https://stackoverflow.com/questions/25835643/replace-missing-values-with-column-mean – Karthik S Sep 29 '20 at 17:52

2 Answers2

0

You may try

library(dplyr)
library(zoo)

df %>%
  na.aggregate()

this will replace all NA values with the mean of each column

Ivn Ant
  • 135
  • 8
  • what exactly is not working? what is the error message ? did you install the librarys before running the code? – Ivn Ant Sep 30 '20 at 12:19
  • Actually there is no error, but when i make for example a str(df) to see some values of the variable, The NA´s are still there. – AdrianGI Sep 30 '20 at 13:28
  • can you provide an example of your data, e.g. with `dput()` ? – Ivn Ant Sep 30 '20 at 13:39
0
NA2mean <- function(x) replace(x, is.na(x), mean(x, na.rm = TRUE))
df<-replace(df, TRUE, lapply(df, NA2mean))

the answer

Ivn Ant
  • 135
  • 8
AdrianGI
  • 39
  • 4