Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
516 views
in Technique[技术] by (71.8m points)

r - `print` function in `ifelse`

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...