if 语句中的几个 paste() 调用,第一个调用不起作用,但第二个调用起作用

问题描述 投票:0回答:1

这篇文章 Paste() function in loop/if seems not working as intended in R 让我试图理解 paste() 在 if 语句中是如何工作的。

我在那篇文章上的回答绝对是我也是的答案,但评论只是没有捕捉到格式,所以这里是问题:

paste 在 if () 语句中的行为如何?

我正在打印第二个粘贴,但不是第一个。我希望第一个打印出来,而不是第二个。

x <- 1
y <- 2

if(x < y){

  print("test print")
  
  paste("Test paste...x is:", x)  #why doesn't this print, but the next paste does? 
  
  paste("Y  is:", y)
}


[1] "test print"
[1] "Y  is: 2" 

为什么第一个粘贴线没有打印出来,而第二个打印出来了?

编辑:

即使我删除了所有打印调用,第一个粘贴也不会打印,但第二个粘贴:

x=1
y=2
if(x<y){

paste("Test paste, x is :", x)
paste("2nd test paste, y  is:", y)
}

[1] "2nd test paste, y  is: 2"
r if-statement paste
1个回答
1
投票

你误解了

paste()
的作用。它never打印任何东西。它只是计算一个字符向量。

如果该计算恰好是在控制台输入的大括号中代码块的最后一行,则将打印其值。

这类似于 R 函数中发生的情况:您可以在那里随意调用

paste()
,但不会打印任何内容。如果函数中的最后一条语句恰好是对
paste()
的调用,那么函数将返回该值。如果函数调用恰好是顶级语句块中的最后(或唯一)语句,自动打印将打印它。

© www.soinside.com 2019 - 2024. All rights reserved.