-6ren">
gpt4 book ai didi

r - dplyr: mutate() 和 mutate_if()

转载 作者:行者123 更新时间:2023-12-01 08:23:54 27 4
gpt4 key购买 nike

我想将列中的所有 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))

但这不会:
> 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

最佳答案

那不是什么mutate_if做。它基于列而不是行,因此与 ifelse 的工作方式不同内mutate .全部替换NA s 与 0 s 在数字列中,尝试例如:

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

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

关于r - dplyr: mutate() 和 mutate_if(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42849849/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com