在R中,我可以停止打印(cat(""))返回NULL吗?为什么cat("foo")会返回foo>

Dav*_*uer 18 r concatenation paste cat

如果我进入

print(cat(""))
Run Code Online (Sandbox Code Playgroud)

我明白了

NULL
Run Code Online (Sandbox Code Playgroud)

我想用来cat()打印R脚本的进度,但我不明白为什么它会NULL在我所有连接字符串的末尾返回,更重要的是,如何让它停止?

Jos*_*ich 13

您的所有答案都在文档中?cat.回答您特定问题的部分是:

参数:

fill: a logical or (positive) numeric controlling how the output is
      broken into successive lines.  If ‘FALSE’ (default), only
      newlines created explicitly by ‘"\n"’ are printed.
      Otherwise, the output is broken into lines with print width
      equal to the option ‘width’ if ‘fill’ is ‘TRUE’, or the value
      of ‘fill’ if this is numeric.  Non-positive ‘fill’ values
      are ignored, with a warning.
Run Code Online (Sandbox Code Playgroud)

......而且......

值:

 None (invisible ‘NULL’).
Run Code Online (Sandbox Code Playgroud)

所以你不能停止print(cat(...))回来,NULL因为这是cat回归.你需要明确添加新行cat("foo\n").

  • 感谢您的回答 - 我在发布问题之前确实阅读了文档,但我仍然不清楚是否有办法阻止它打印“NULL”或为什么它打印 null 或者为什么值是“None”甚至虽然它清楚地返回了提供的字符串......我想我的一些误解更多地与理论有关而不是与实际有关。 (2认同)
  • 好吧,文档可以简洁,`print`和`cat`看起来像是做类似的事情.但是`cat` _does not_返回提供的字符串,它_prints_它.微妙但重要的差异.在"另请参阅"部分中查看功能的文档页面也是一种很好的做法. (2认同)
  • @ucfagls:你不需要两个`cat(paste(...))`.`cat`自动用空格分隔参数...这节省了一些输入.;-) (2认同)

d11*_*d11 8

NULL是"cat()"的返回值.如果省略外部"print()",则不会看到NULL.


Cho*_*ens 7

我有完全相同的问题.简而言之,cat()在R下有点不知所措.你没有详细介绍你如何使用,cat()但我建议你看看paste().

?paste

我想这可能就是你要找的东西.

  • @David - 该 R 帮助消息中示例的 `paste()` 版本将是:`writeLines(paste("msg1","msg2", sep = "\n"))`。使用 `cat()` 的版本不是很好,因为你必须添加一个额外的 `"\n"`:`cat(paste("msg1","msg2","\n", sep = "\n" ))` 或 `cat(paste("msg1","msg2", sep = "\n"), "\n")` (2认同)

Mas*_*edi 5

我认为不需要使用print(cat()).打印消息 cat()已经足够了.这可能是您正在寻找的:

  for (j in 1:n) {
     cat("Running loop", j, "of", n, "\n")
  }
Run Code Online (Sandbox Code Playgroud)