I'm wondering why ifelse(1<2,print("true"),print("false"))
returns
[1] "true"
[1] "true"
whereas ifelse(1<2,"true","false")
returns
[1] "true"
I don't understand why the print
within ifelse
returns "true"
twice
This happens because ifelse
will always return a value. When you run ifelse(1<2,print("true"),print("false"))
, your yes
condition is chosen. This condition is a function call to print "true"
on the console, and so it does.
But the print()
function also returns its argument, but invisibly (like assignments, for example), otherwise you'd have the value printed twice in some cases. When the yes
expression is evaluated, its result is what ifelse
returns, and ifelse
does not returns invisibly, so, it prints the result, since that was ran on the Global Environment and without any assignment.
We can test some variations and check what's going on.
> result <- print("true")
[1] "true" # Prints because the print() function was called.
> result
[1] "true" # The print function return its argument, which was assigned to the variable.
> ifelse(1<2, {print("true");"TRUE"},print("false"))
[1] "true" #This was printed because print() was called
[1] "TRUE" #This was printed because it was the value returned from the yes argument
If we assign this ifelse()
> result <- ifelse(1<2, {print("true");"TRUE"},print("false"))
[1] "true"
> result
[1] "TRUE"
We can also look at the case where both conditions conditions are evaluated:
> ifelse(c(1,3)<2, {print("true");"TRUE"},{print("false");"FALSE"})
[1] "true" # The yes argument prints this
[1] "false" # The no argument prints this
[1] "TRUE" "FALSE" # This is the returned output from ifelse()
You should use ifelse
to create a new object, not to perform actions based on a condition. For that, use if
else
. The R Inferno has good section (3.2) on the difference between the two.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With