Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mutate_at to replace NAs with 0

Tags:

r

dplyr

mtcars1 <- mtcars %>% 
  mutate(blah = LETTERS[seq(1,26, length.out = nrow(.))],
         blah2 = letters[seq(1,26, length.out = nrow(.))])

# sprinkle some random NA values
mtcars1$blah[c(1,3,5,10,11)] <- NA
mtcars1$blah2[c(1,2,5,15,20)] <- NA


mtcars1 %>% 
  mutate_at(blah:blah2, function(x) {
    if_else(is.na(x), 0, x)
  })

Returns:

Error in check_dot_cols(.vars, .cols) : object 'blah' not found

How can I replace NAs with 0 across multiple columns using dplyr/tidyverse approach?

like image 480
Doug Fir Avatar asked Oct 25 '19 18:10

Doug Fir


1 Answers

We can wrap the ranger of column names in vars and also make sure that the return types are the same for if_else (or case_when) based on the documentation of ?if_else

Compared to the base ifelse(), this function is more strict. It checks that true and false are the same type. This strictness makes the output type more predictable, and makes it somewhat faster.

library(dplyr)
mtcars1 %>% 
    mutate_at(vars(blah:blah2),  ~ if_else(is.na(.), '0', .))

Here, instead of the anonymous function call (function(x)), the tidyverse concise option with ~ is used and as 'blah', 'blah2' are character types, the return type for true is also quoted ('0')


Instead of if_else, another option specifically for replacing NA is replace_na from tidyr

library(tidyr)
mtcars1 %>% 
    mutate_at(vars(blah:blah2),  replace_na, '0')
like image 184
akrun Avatar answered Sep 28 '22 21:09

akrun