Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace NA on numeric columns with mutate_if and replace_na

Tags:

r

tidyverse

I would like to replace NAs in numeric columns using some variation of mutate_if and replace_na if possible, but can't figure out the syntax.

df <-tibble(
    first = c("a", NA, "b"),
    second = c(NA, 2, NA),
    third = c(10, NA, NA)
  )

#> # A tibble: 3 x 3
#>   first second third
#>   <chr>  <dbl> <dbl>
#> 1 a      NA     10.0
#> 2 <NA>    2.00  NA  
#> 3 b      NA     NA

Final result should be:

#> # A tibble: 3 x 3
#>   first second third
#>   <chr>  <dbl> <dbl>
#> 1 a       0     10.0
#> 2 <NA>    2.00   0  
#> 3 b       0      0

My attempts look like:

df %>% mutate_if(is.numeric , replace_na(., 0) )
#>Error: is_list(replace) is not TRUE
like image 509
Nettle Avatar asked Mar 17 '18 21:03

Nettle


2 Answers

df %>% mutate_if(is.numeric , replace_na, replace = 0)

# A tibble: 3 x 3
#  first second third
#  <chr>  <dbl> <dbl>
#1 a       0     10.0
#2 NA      2.00   0  
#3 b       0      0  
like image 50
Lyngbakr Avatar answered Nov 09 '22 02:11

Lyngbakr


The in another answer mentioned solution based on mutate_if is based on a suspended function in dplyr. The suggested alternative is to use the across() function. Here a solution using that one:

df %>% 
  mutate(
    across(where(is.numeric), ~replace_na(.x, 0))
  )

# A tibble: 3 × 3
  first second third
  <chr>  <dbl> <dbl>
1 a          0    10
2 NA         2     0
3 b          0     0
like image 23
Jochem Avatar answered Nov 09 '22 01:11

Jochem