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?
We can wrap the ranger of column names in vars
and also make sure that the return type
s 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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With