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

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


当前回答

另一个选项使用sapply将所有NA替换为零。下面是一些可重复的代码(数据来自@aL3xa):

set.seed(7) # for reproducibility
m <- matrix(sample(c(NA, 1:10), 100, replace = TRUE), 10)
d <- as.data.frame(m)
d
#>    V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
#> 1   9  7  5  5  7  7  4  6  6   7
#> 2   2  5 10  7  8  9  8  8  1   8
#> 3   6  7  4 10  4  9  6  8 NA  10
#> 4   1 10  3  7  5  7  7  7 NA   8
#> 5   9  9 10 NA  7 10  1  5 NA   5
#> 6   5  2  5 10  8  1  1  5 10   3
#> 7   7  3  9  3  1  6  7  3  1  10
#> 8   7  7  6  8  4  4  5 NA  8   7
#> 9   2  1  1  2  7  5  9 10  9   3
#> 10  7  5  3  4  9  2  7  6 NA   5
d[sapply(d, \(x) is.na(x))] <- 0
d
#>    V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
#> 1   9  7  5  5  7  7  4  6  6   7
#> 2   2  5 10  7  8  9  8  8  1   8
#> 3   6  7  4 10  4  9  6  8  0  10
#> 4   1 10  3  7  5  7  7  7  0   8
#> 5   9  9 10  0  7 10  1  5  0   5
#> 6   5  2  5 10  8  1  1  5 10   3
#> 7   7  3  9  3  1  6  7  3  1  10
#> 8   7  7  6  8  4  4  5  0  8   7
#> 9   2  1  1  2  7  5  9 10  9   3
#> 10  7  5  3  4  9  2  7  6  0   5

使用reprex v2.0.2创建于2023-01-15


请注意:从R 4.1.0开始,您可以使用\(x)而不是函数(x)。

其他回答

如果你想在因子变量中替换NAs,这可能是有用的:

n <- length(levels(data.vector))+1

data.vector <- as.numeric(data.vector)
data.vector[is.na(data.vector)] <- n
data.vector <- as.factor(data.vector)
levels(data.vector) <- c("level1","level2",...,"leveln", "NAlevel") 

它将因子向量转换为数值向量,并添加另一个人工数值因子水平,然后将其转换回具有您选择的额外“na水平”的因子向量。

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

定义这个函数:

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

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

na.zero(some.vector)

在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   

DPLYR >= 1.0.0

在dplyr的新版本中:

Across()取代了一系列“作用域变量”,如summarise_at()、summarise_if()和summarise_all()。

df <- data.frame(a = c(LETTERS[1:3], NA), b = c(NA, 1:3))

library(tidyverse)

df %>% 
  mutate(across(where(anyNA), ~ replace_na(., 0)))

  a b
1 A 0
2 B 1
3 C 2
4 0 3

这段代码将强制0为第一列中的字符。要根据列类型替换NA,您可以使用类似呜呜声的公式,其中:

df %>% 
  mutate(across(where(~ anyNA(.) & is.character(.)), ~ replace_na(., "0")))

dplyr例子:

library(dplyr)

df1 <- df1 %>%
    mutate(myCol1 = if_else(is.na(myCol1), 0, myCol1))

注意:这适用于每个选定的列,如果我们需要对所有列都这样做,请参阅@reidjax的答案使用mutate_each。