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

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


当前回答

不需要使用任何库。

df <- data.frame(a=c(1,3,5,NA))

df$a[is.na(df$a)] <- 0

df

其他回答

你可以使用replace()

例如:

> x <- c(-1,0,1,0,NA,0,1,1)
> x1 <- replace(x,5,1)
> x1
[1] -1  0  1  0  1  0  1  1

> x1 <- replace(x,5,mean(x,na.rm=T))
> x1
[1] -1.00  0.00  1.00  0.00  0.29  0.00 1.00  1.00

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

定义这个函数:

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

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

na.zero(some.vector)

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

我个人用过,效果很好:

players_wd$APPROVED_WD[is.na(players_wd$APPROVED_WD)] <- 0

一个简单的方法是用if_na from hablar:

library(dplyr)
library(hablar)

df <- tibble(a = c(1, 2, 3, NA, 5, 6, 8))

df %>% 
  mutate(a = if_na(a, 0))

返回:

      a
  <dbl>
1     1
2     2
3     3
4     0
5     5
6     6
7     8