You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
It appears to me that if_else evaluates both the true and false arguments, and then returns only the one that matches the condition argument. This differs from ifelse which appears to only evaluate the true or false argument that matches the condition argument.
This is a problem if if_else is being used to avoid evaluating an expression that is know to fail in certain situations. Is this necessary to ensure "that true and false are the same type."? What would be a tidyverse way of handling this?
x<-list("a", 1, 2, "b")
sapply(x, function(x) ifelse(is.numeric(x), x+1, NaN))
#> [1] NaN 2 3 NaN
sapply(x, function(x) dplyr::if_else(is.numeric(x), x+1, NaN))
#> Error in x + 1: non-numeric argument to binary operator
What does happen is that if condition is only TRUE (or only FALSE), then the result vector that isn't needed won't be evaluated. But you can't rely on this, of course.
if_else() does not have short-circuiting semantics. Use if () if you need short-circuiting. It is necessary to compute both sides of the condition to figure out the return type. The code you have reported is a type error. In my opinion it is also a bit hard to understand because it relies on a strange mix of scalar predicate and recycling.
It appears to me that
if_else
evaluates both thetrue
andfalse
arguments, and then returns only the one that matches thecondition
argument. This differs fromifelse
which appears to only evaluate thetrue
orfalse
argument that matches thecondition
argument.This is a problem if
if_else
is being used to avoid evaluating an expression that is know to fail in certain situations. Is this necessary to ensure "thattrue
andfalse
are the same type."? What would be atidyverse
way of handling this?Created on 2020-06-19 by the reprex package (v0.3.0)
The text was updated successfully, but these errors were encountered: