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

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


当前回答

专用函数nafill和setnafill,用于此目的,在data.table中。 只要可用,它们就将列分发到多个线程上进行计算。

library(data.table)

ans_df <- nafill(df, fill=0)

# or even faster, in-place
setnafill(df, fill=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

另一个与tidyrmethod replace_na兼容的dplyr管道选项,适用于多个列:

require(dplyr)
require(tidyr)

m <- matrix(sample(c(NA, 1:10), 100, replace = TRUE), 10)
d <- as.data.frame(m)

myList <- setNames(lapply(vector("list", ncol(d)), function(x) x <- 0), names(d))

df <- d %>% replace_na(myList)

你可以很容易地限制到例如数字列:

d$str <- c("string", NA)

myList <- myList[sapply(d, is.numeric)]

df <- d %>% replace_na(myList)

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

更通用的方法是在矩阵或向量中使用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))

我个人用过,效果很好:

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