gpt4 book ai didi

r - `print` 函数在 `ifelse`

转载 作者:行者123 更新时间:2023-12-04 00:58:15 25 4
gpt4 key购买 nike

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

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

ifelse(1<2,"true","false")返回
[1] "true"

我不明白为什么 printifelse返回 "true"两次

最佳答案

这是因为 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

如果我们分配这个 ifelse()
> result <- ifelse(1<2, {print("true");"TRUE"},print("false"))
[1] "true"
> result
[1] "TRUE"

我们还可以看看两个条件条件都被评估的情况:
> 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创建一个新对象,而不是根据条件执行操作。为此,请使用 if else . The R Inferno关于两者之间的区别有很好的第(3.2)节。

关于r - `print` 函数在 `ifelse`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31630642/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com