`ifelse`中的`print`函数

Gau*_*man 12 if-statement r

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

[1] "true"
[1] "true"
Run Code Online (Sandbox Code Playgroud)

ifelse(1<2,"true","false")回报

[1] "true"
Run Code Online (Sandbox Code Playgroud)

我不明白为什么print内部ifelse返回"true"两次

Mol*_*olx 13

这是因为ifelse将始终返回一个值.当你跑步时ifelse(1<2,print("true"),print("false")),你的yes病情就会被选中.这个条件是"true"在控制台上打印的函数调用,所以它确实如此.

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

我们可以测试一些变化并检查发生了什么.

> 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
Run Code Online (Sandbox Code Playgroud)

如果我们分配这个 ifelse()

> result <- ifelse(1<2, {print("true");"TRUE"},print("false"))
[1] "true"
> result
[1] "TRUE"
Run Code Online (Sandbox Code Playgroud)

我们还可以看一下评估两种条件条件的情况:

> 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()
Run Code Online (Sandbox Code Playgroud)

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


drm*_*iod -1

不是同时打印TRUE并返回TRUE吗?

例如,使用 cat 而不是 print 会改变输出......

这基本上与ulfelders的评论有关。