`ifelse`中的`print`函数 [英] `print` function in `ifelse`

查看:253
本文介绍了`ifelse`中的`print`函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么 ifelse(1< 2,print(true),print(false))返回

[1] "true"
[1] "true"

ifelse(1< 2,true,false)返回

[1] "true"

I不明白为什么打印 ifelse 返回true两次

I don't understand why the print within ifelse returns "true" twice

推荐答案

这是因为 ifelse 将始终返回一个值。当你运行 ifelse(1< 2,print(true),print(false))时,你的选择条件。这个条件是在控制台上打印true的函数调用,所以它确实如此。

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.

但是 print()函数也返回其参数,但不可见(例如,分配),否则在某些情况下您将打印两次值。当评估 yes 表达式时,其结果是 ifelse 返回, ifelse 不会无形地返回,因此,它会打印结果,因为它是在全局环境中运行的,没有任何赋值。

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

如果我们分配此 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()

您应该使用 ifelse 来创建新对象,而不是执行基于操作的操作有条件的。为此,如果 else ,请使用 R Inferno 对于两者之间的差异有很好的部分(3.2) 。

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.

这篇关于`ifelse`中的`print`函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆