Home > Enterprise >  Replace NA values in data frame with the column mean
Replace NA values in data frame with the column mean

Time:03-11

please, I want to change all NA values in column by column mean. But i don't know where i have to put condition [is.na(df1()input$to_mean)] in my code. My code works but all values in column are changed (logically) but i need replace only NA values. Can someone help?

observeEvent(input$NA_mean, {
    df1(df1() %>% mutate(!!input$to_mean := mean(df1()[[input$to_mean]], na.rm = T)))
  })

#this code change all values in column to column mean, i need replace only NA values ([is.na(df1()input$to_mean)])

CodePudding user response:

library(tidyverse)
df1 <- tibble(x = seq(3), y = c(1, NA, 2))
df1 %>% mutate(y = y %>% replace_na(mean(df1$y, na.rm = TRUE)))
#> # A tibble: 3 × 2
#>       x     y
#>   <int> <dbl>
#> 1     1   1  
#> 2     2   1.5
#> 3     3   2

Created on 2022-03-10 by the reprex package (v2.0.0)

  • Related