简体   繁体   中英

dplyr: mutate() and mutate_if()

I want to change all NAs in columns to 0. I can do it with mutate() , but not with mutate_if() .

This works:

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

But this doesn't:

> 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

That is not what mutate_if does. It predicates on columns not rows, and therefore does not work the same as the ifelse within mutate . To replace all NA s with 0 s in numeric columns, try eg:

test %>% mutate_if(is.numeric, funs(ifelse(is.na(.), 0, .)))

Or

test %>% mutate_if(is.numeric, coalesce, ... = 0)

OR:

library(tidyr)
replace_na(list(Q3.2 = 0, Q8.2 = 0))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM