我正在探索cat()
和message()
格式化函数输出格式的可能性。
当我使用cat(fill = TRUE)
时,将在消息末尾添加新行,以方便后续消息的打印。当我设置fill = FALSE
时,这些消息将打印在同一行中。
由于某种原因,当我非交互地运行代码并通过rmarkdown将代码编织到该代码时,此打印行为会改变。 现在单行中的消息现在已被多行分开-我无法弄清楚为什么或如何解决此问题。(在Rstudio中,交互式会话不是这种情况)
请参见下面的最小示例,并尝试交互操作以查看区别。
print_messages <- function(newline = TRUE){
cat("1st line", fill = newline)
message("2nd line")
}
print_messages()
#> 1st line
#> 2nd line
print_messages(newline = FALSE) # this is, where the difference occurs
#> 1st line
#> 2nd line
print_messages <- function(newline = TRUE){
cat("1st line", fill = newline)
message("2nd line")
}
print_messages()
#> 1st line
#> 2nd line
print_messages(newline = FALSE) # this is, where the difference occurs
#> 1st line2nd line
由reprex package(v0.2.1)于2019-02-04创建
答案 0 :(得分:1)
这是由于以下事实:正常的块输出和消息在相应的hooks中被分别处理。在此过程中,在\n
和cat()
的输出前后插入换行符(message()
)。您可以通过在RMarkdown文档的开头执行以下操作来阐明这一点:
```{r, echo = F}
defMessageHook <- knitr::knit_hooks$get("message")
knitr::knit_hooks$set(message = function(x, options) {
x <- defMessageHook(x, options) # Apply default hook
print(x)
return(x)
})
```
在这里,我们保存默认消息挂钩并重新定义它。在新的挂钩中,我们应用默认挂钩并添加print()
语句,以查看默认挂钩是由我们的消息产生的(检查控制台旁边的R Markdown面板):
[1] "\n\n```\n## 2nd line\n```\n\n"
[1] "\n\n```\n## 2nd line\n```\n\n"
如您所见,Markdown代码块由换行符包裹。