How to replace all NA in a dataframe using tidyr::replace_na?

zesla picture zesla · Aug 8, 2017 · Viewed 48.5k times · Source

I'm trying to fill all NAs in my data with 0's. Does anyone know how to do that using replace_na from tidyr? From documentation, we can easily replace NA's in different columns with different values. But how to replace all of them with some value? I have many columns...

Using mtcars dataset as an example:

mtcars [sample(1:nrow(mtcars), 4), sample(1:ncol(mtcars), 4)]<- NA
mtcars %>% replace_na( ??? )

Answer

Sagar picture Sagar · Aug 8, 2017

If replace_na is not a mandatory requirement, following code will work:

mtcars %>% replace(is.na(.), 0)

Reference Issue: https://stackoverflow.com/a/45574804/8382207