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

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


当前回答

你可以使用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

其他回答

也可以使用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))) 

一个简单的方法是用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

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

要替换一个数据帧中的所有NAs,你可以使用:

Df %>% replace(is.na(.), 0)

对于单个向量:

x <- c(1,2,NA,4,5)
x[is.na(x)] <- 0

对于data.frame,在上面的基础上创建一个函数,然后将其应用到列上。

下次请提供一个可重复的例子,具体如下:

如何制作一个优秀的R可复制示例?