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

后端 未结 20 1983
说谎
说谎 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:05

    With dplyr 0.5.0, you can use coalesce function which can be easily integrated into %>% pipeline by doing coalesce(vec, 0). This replaces all NAs in vec with 0:

    Say we have a data frame with NAs:

    library(dplyr)
    df <- data.frame(v = c(1, 2, 3, NA, 5, 6, 8))
    
    df
    #    v
    # 1  1
    # 2  2
    # 3  3
    # 4 NA
    # 5  5
    # 6  6
    # 7  8
    
    df %>% mutate(v = coalesce(v, 0))
    #   v
    # 1 1
    # 2 2
    # 3 3
    # 4 0
    # 5 5
    # 6 6
    # 7 8
    

提交回复
热议问题