dplyr:mutate()和mutate_if()

use*_*966 3 r dplyr

我想将列中的所有NA更改为0.我可以使用mutate(),但不能使用mutate_if().

这有效:

> test <- tibble(Q3.2 = c(1,2, NA, NA, 3),
                             Q8.2 = c(2, NA, 1, NA, 4))

> test %>% select_("Q3.2", "Q8.2") %>%
    mutate(Q3.2 = ifelse(is.na(Q3.2), 0, Q3.2),
           Q8.2 = ifelse(is.na(Q8.2), 0, Q8.2))
Run Code Online (Sandbox Code Playgroud)

但这不是:

> test %>% select_("Q3.2", "Q8.2") %>%
+     mutate_if(is.na(.), 0, .)
Error in get(as.character(FUN), mode = "function", envir = envir) : 
  object 'p' of mode 'function' was not found
Run Code Online (Sandbox Code Playgroud)

Axe*_*man 7

那不是什么mutate_if意思.它预测列而不是行,因此不能与ifelse内部相同mutate.NA要用0数字列中的s 替换所有s ,请尝试例如:

test %>% mutate_if(is.numeric, funs(ifelse(is.na(.), 0, .)))
Run Code Online (Sandbox Code Playgroud)

要么

test %>% mutate_if(is.numeric, coalesce, ... = 0)
Run Code Online (Sandbox Code Playgroud)