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

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


当前回答

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")))

其他回答

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

不需要使用任何库。

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

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

df

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

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")))

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