hange values "in" by media in dataframe column

Hello community.
I have the following problem:

I need to change the NA values ​​of some columns in the dataframe for their averages.
wanted without having to repeat code


 first_column <- c("A","B", "C","A","A")
 second_column <- c(1, 2,2,3, NA) 
 third_column <- c(1, 4,NA,3, NA) 
 df<-  data.frame(first_column, second_column, third_column)








Is this what you mean?

library(dplyr)

df <- data.frame(
  stringsAsFactors = FALSE,
      first_column = c("A", "B", "C", "A", "A"),
     second_column = c(1, 2, 2, 3, NA),
      third_column = c(1, 4, NA, 3, NA)
)

df %>% 
    mutate(across(where(is.numeric),
                  ~if_else(is.na(.), mean(., na.rm = TRUE), .)
                  )
           )
#>   first_column second_column third_column
#> 1            A             1     1.000000
#> 2            B             2     4.000000
#> 3            C             2     2.666667
#> 4            A             3     3.000000
#> 5            A             2     2.666667

Created on 2020-07-01 by the reprex package (v0.3.0)

@andresrcs

It was what I was looking for. Thank you

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.