我有一个数据帧和一些列有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

其他回答

如果我们试图在导出时替换NAs,例如写入csv时,那么我们可以使用:

  write.csv(data, "data.csv", na = "0")

在dplyr 0.5.0中,你可以使用coalesce函数,通过做coalesce(vec, 0)可以很容易地集成到%>%管道中。这将把vec中的所有NAs替换为0:

假设我们有一个带NAs的数据帧:

library(dplyr)
df <- data.frame(v = c(1, 2, 3, NA, 5, 6, 8))

df
#    v
# 1  1
# 2  2
# 3  3
# 4 NA
# 5  5
# 6  6
# 7  8

df %>% mutate(v = coalesce(v, 0))
#   v
# 1 1
# 2 2
# 3 3
# 4 0
# 5 5
# 6 6
# 7 8

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

这是一个更灵活的解决方案。不管你的数据帧有多大,它都能工作,或者用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`

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