我有一个数据帧和一些列有NA值。

我如何将这些NA值替换为零?


当前回答

取代。数据帧中的na和NULL。

带列的数据帧

A name(美元是na (A name) < 0美元。

OR

A $ name[是na (A $ name) < - " na "

所有数据帧

自由度[is.na(DF)]<-0

将数据帧中的na替换为空白

df[is.na(df)]<-“”

将NULL替换为NA

df[is.null(df)] <- NA

其他回答

也可以使用tidyr::replace_na。

    library(tidyr)
    df <- df %>% mutate_all(funs(replace_na(.,0)))

编辑(dplyr > 1.0.0):

df %>% mutate(across(everything(), .fns = ~replace_na(.,0))) 

更通用的方法是在矩阵或向量中使用replace()将NA替换为0

例如:

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

这也是在dplyr中使用ifelse()的一种替代方法

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

cleaner包有一个na_replace()泛型,默认情况下将数值替换为0,将逻辑替换为FALSE,将日期替换为今天,等等:

library(dplyr)
library(cleaner)

starwars %>% na_replace()
na_replace(starwars)

它甚至支持矢量化替换:

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

文档:https://msberends.github.io/cleaner/reference/na_replace.html

我知道这个问题已经有了答案,但这样做可能对一些人更有用:

定义这个函数:

na.zero <- function (x) {
    x[is.na(x)] <- 0
    return(x)
}

现在,无论何时你需要将向量中的NA转换为0,你可以这样做:

na.zero(some.vector)

这是一个更灵活的解决方案。不管你的数据帧有多大,它都能工作,或者用0或0来表示0。

library(dplyr) # make sure dplyr ver is >= 1.00

df %>%
    mutate(across(everything(), na_if, 0)) # if 0 is indicated by `zero` then replace `0` with `zero`