R `在ifelse中打印`函数`

R `在ifelse中打印`函数`,r,if-statement,R,If Statement,我想知道为什么ifelse(1不是同时打印TRUE和返回TRUE吗 例如,使用cat而不是print会改变输出 这基本上与注释有关。发生这种情况是因为ifelse将始终返回一个值。当您运行ifelse(1 ifelse(c(1,3)只是为了给Molx的优秀答案添加一些参数。 发生这种情况的原因之一在于: length(print("true")) [1] "true" [1] 1 length(length(print("true"))) [1] "true" [1] 1 length(leng

我想知道为什么ifelse(1不是同时打印TRUE和返回TRUE吗

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


这基本上与注释有关。

发生这种情况是因为
ifelse
将始终返回一个值。当您运行
ifelse(1 ifelse(c(1,3)只是为了给Molx的优秀答案添加一些参数。
发生这种情况的原因之一在于:

length(print("true"))
[1] "true"
[1] 1
length(length(print("true")))
[1] "true"
[1] 1
length(length(length(print("true"))))
[1] "true"
[1] 1
……等等

R手册中规定:

是测试的真实元素的返回值

注意,而不是,这里我们有两个值:一个是打印函数的对象(必须打印“true”,很可能是对函数的调用,在本例中为
打印
,结果是字符向量为
),另一个是输出打印“true”哪个是
ifelse
语句的正确元素

可以通过以下方式避免:

 ifelse(1 < 2, "true" , "false" )
[1] "true"
ifelse(1<2,“真”、“假”)
[1] “对”

可能与相关。还请注意,
ifelse
设计用于向量,而不是标量,因此最好使用
if(1注意,如果你指定了它,就像一个古老的传说说,每当一个非程序员的家伙说“bug”这个词时,一个程序员就死了。你必须拍手让他活过来。
ifelse(1<2,print(print(“true”)),print(“false”))
是查看正在发生的情况的另一种方法。然后反转运算符。mmm use
cat
将抛出错误消息和警告,因为它解释了其参数;请尝试
ifelse(1非常感谢您的否决票。通常,否决票后不会有评论。这一部分不正确:这里我们有两个值:一个是打印函数的对象(必须打印“true”),另一个是打印“true”。有两个不同的向量,每个元素一个,第二个向量是
ifelse()
的唯一结果。第一个向量只是
print()
的结果,不是
ifelse()结果的一部分
一点也不。@RichardScribe即使我已经编辑了这个问题,现在我认为它更清楚了。我们的想法是一样的,也许我没有写清楚。我知道现在它清楚了。
> 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
> 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()
length(print("true"))
[1] "true"
[1] 1
length(length(print("true")))
[1] "true"
[1] 1
length(length(length(print("true"))))
[1] "true"
[1] 1
 ifelse(1 < 2, "true" , "false" )
[1] "true"