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

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

    If you want to replace NAs in factor variables, this might be useful:

    n <- length(levels(data.vector))+1
    
    data.vector <- as.numeric(data.vector)
    data.vector[is.na(data.vector)] <- n
    data.vector <- as.factor(data.vector)
    levels(data.vector) <- c("level1","level2",...,"leveln", "NAlevel") 
    

    It transforms a factor-vector into a numeric vector and adds another artifical numeric factor level, which is then transformed back to a factor-vector with one extra "NA-level" of your choice.

提交回复
热议问题