Replacing NA's in a dataframe/tibble


#1

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.


#2

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


#3

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)))


replacing NA with for loop vs dplyr
#4

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


#5

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!


replacing NA with for loop vs dplyr
#6

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


closed #7

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