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

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


当前回答

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

其他回答

这个从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)

我个人用过,效果很好:

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

在data.frame中,不需要通过突变来创建新列。

library(tidyverse)    
k <- c(1,2,80,NA,NA,51)
j <- c(NA,NA,3,31,12,NA)
        
df <- data.frame(k,j)%>%
   replace_na(list(j=0))#convert only column j, for example
    

结果

k   j
1   0           
2   0           
80  3           
NA  31          
NA  12          
51  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))

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

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