Replacing NA's in a dataframe/tibble

I've been using the following code to replace NA's with zeros:

mutate_all(funs(replace(., is.na(.), 0)))

Is there some more elegant option out there?

Thanks for your help.

tidyr::replace_na() may be helpful (if your number of variables is not too large + cumbersome to write out manually)!

2 Likes

Thanks for the suggestion to look again at replace_na. After some more experimentation these worked well and are slightly simpler:

mutate_all(funs(replace_na(., 0)))
mutate_if(is.numeric, funs(replace_na(., 0)))

3 Likes

Oh right, I forgot you could use mutate_all + replace_na and not have to type them all out :laughing:

That's a good solution. I've been using:

df[is.na(df)] <- 0 

but it does not fit in a pipe chain very smoothly. I really like

mutate_if(is.numeric, funs(replace_na(., 0)))

thanks for sharing what you figured out!

6 Likes

If your question's been answered (even if by you), would you mind choosing a solution? (See FAQ below for how).

Having questions checked as resolved makes it a bit easier to navigate the site visually and see which threads still need help.

Thanks

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.