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

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


当前回答

这个从Datacamp中提取的简单函数可以帮助:

replace_missings <- function(x, replacement) {
  is_miss <- is.na(x)
  x[is_miss] <- replacement

  message(sum(is_miss), " missings replaced by the value ", replacement)
  x
}

Then

replace_missings(df, replacement = 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))

如果您想在更改特定列(本例中为列V3)中的NAs后分配一个新名称,也可以这样做

my.data.frame$the.new.column.name <- ifelse(is.na(my.data.frame$V3),0,1)

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

定义这个函数:

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

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

na.zero(some.vector)

不需要使用任何库。

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

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

df

在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