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

后端 未结 20 1948
说谎
说谎 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

    Another dplyr pipe compatible option with tidyrmethod replace_na that works for several columns:

    require(dplyr)
    require(tidyr)
    
    m <- matrix(sample(c(NA, 1:10), 100, replace = TRUE), 10)
    d <- as.data.frame(m)
    
    myList <- setNames(lapply(vector("list", ncol(d)), function(x) x <- 0), names(d))
    
    df <- d %>% replace_na(myList)
    

    You can easily restrict to e.g. numeric columns:

    d$str <- c("string", NA)
    
    myList <- myList[sapply(d, is.numeric)]
    
    df <- d %>% replace_na(myList)
    

提交回复
热议问题