Home > Back-end >  Why does `ifelse()` behave differently than `if (cond) {...} else {...}`
Why does `ifelse()` behave differently than `if (cond) {...} else {...}`

Time:12-09

I was trying to generate uniform input arguments for a function (no matter if a user inputs numeric values or a unit object, the function should continue with a unit object), when I stumbled across this behaviour I cannot really explain right now:

# case 1 ---
t <- 20

# expected output: 20 [°C]: fail
ifelse(inherits(t, "units"),
       t,
       units::as_units(t, "°C"))
#> [1] 20

# case 2 ---
t <- units::as_units(20, "°C")

# expected output: 20 [°C]: fail
ifelse(inherits(t, "units"),
       t,
       units::as_units(t, "°C"))
#> [1] 20

# case 3 ---
t <- 20

# expected output: 20 [°C]: everything OK
if (inherits(t, "units")) t else units::as_units(t, "°C")
#> 20 [°C]

# case 4 ---
t <- units::as_units(20, "°C")

# expected output: 20 [°C]: everything OK
if (inherits(t, "units")) t else units::as_units(t, "°C")
#> 20 [°C]

What am I missing? Thanks a lot in advance!

CodePudding user response:

This is because ifelse strips attributes. See ?ifelse:

Warning

The mode of the result may depend on the value of test (see the examples), and the class attribute (see oldClass) of the result is taken from test and may be inappropriate for the values selected from yes and no.

In those cases, it's preferable to use if. Again from the documentation:

Further note that if(test) yes else no is much more efficient and often much preferable to ifelse(test, yes, no) whenever test is a simple true/false result, i.e., when length(test) == 1.

  • Related