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
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.
Just to add some arguments to the excellent answer of Molx. One of the reason why that happens relies on this:
length(print("true"))
[1] "true"
[1] 1
length(length(print("true")))
[1] "true"
[1] 1
length(length(length(print("true"))))
[1] "true"
[1] 1
... and so on...
In the R manual is stated that:
yes return values for true elements of test
note the values, and not value, here we have two values : one is the object of the print function (that has to print "true", most likely it is a call to a function, in this case print
, that has as a result a character vector with true
) and another one is the output print "true" which is the proper element of the ifelse
statement.
It could be avoided with just:
ifelse(1 < 2, "true" , "false" )
[1] "true"
Isn't it printing TRUE and returning TRUE at the same time?
So for example using cat instead of print would change the output...
This is basically related to ulfelders comment.