本文介绍了dplyr if_else()与基准R ifelse()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对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()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 21:57