How do I replace NA values with zeros in an R dataframe?

后端 未结 20 1965
说谎
说谎 2020-11-21 23:41

I have a data frame and some columns have NA values.

How do I replace these NA values with zeroes?

20条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-21 23:58

    The cleaner package has an na_replace() generic, that at default replaces numeric values with zeroes, logicals with FALSE, dates with today, etc.:

    starwars %>% na_replace()
    na_replace(starwars)
    

    It even supports vectorised replacements:

    mtcars[1:6, c("mpg", "hp")] <- NA
    na_replace(mtcars, mpg, hp, replacement = c(999, 123))
    

    Documentation: https://msberends.github.io/cleaner/reference/na_replace.html

提交回复
热议问题