问题描述
我对 Tidyverse 相当精通,但一直使用 ifelse()
而不是 dplyr if_else()
.我想切换此行为并默认始终使用 dplyr::if_else()
并从我的代码中弃用 ifelse()
.
I am fairly proficient within the Tidyverse, but have always used ifelse()
instead of dplyr if_else()
. I want to switch this behavior and default to always using dplyr::if_else()
and deprecating ifelse()
from my code.
有什么理由不这样做吗?这可能会给我带来麻烦吗?我会告诉你细节,但最近,当我在我的数据分析中不知不觉地创建了一列字符矩阵时,不使用 if_else()
把我搞砸了.如果我切换到始终使用 if_else()
,我希望将来避免这个问题.
Is there any reason not to do this? Would this likely get me into trouble? I'll spare you the details, but recently, not using if_else()
screwed me up, when I unknowingly created a column of character matrices in my data analysis. If I switch to always using if_else()
I hope to avoid this issue in the future.
推荐答案
if_else
更严格.它检查两个选项是否属于相同类型,否则会抛出错误,而 ifelse
将根据需要提升类型.这在某些情况下可能是一个好处,但如果您不检查错误或明确强制类型转换,则可能会破坏脚本.例如:
if_else
is more strict. It checks that both alternatives are of the same type and otherwise throws an error, while ifelse
will promote types as necessary. This may be a benefit in some circumstances, but may otherwise break scripts if you don't check for errors or explicitly force type conversion. For example:
ifelse(c(TRUE,TRUE,FALSE),"a",3)
[1] "a" "a" "3"
if_else(c(TRUE,TRUE,FALSE),"a",3)
Error: `false` must be type character, not double
这篇关于dplyr if_else() 与基础 R ifelse()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!