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

后端 未结 20 2291
说谎
说谎 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-22 00:15

    More general approach of using replace() in matrix or vector to replace NA to 0

    For example:

    > x <- c(1,2,NA,NA,1,1)
    > x1 <- replace(x,is.na(x),0)
    > x1
    [1] 1 2 0 0 1 1
    

    This is also an alternative to using ifelse() in dplyr

    df = data.frame(col = c(1,2,NA,NA,1,1))
    df <- df %>%
       mutate(col = replace(col,is.na(col),0))
    

提交回复
热议问题