Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does `ifelse()` behave differently than `if (cond) {…} else {…}`

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading