R markdown results='hold' 但对于消息?

Rom*_* B. 7 r r-markdown

我的代码中有输出多条消息的函数,但我无法将这些消息放在同一个输出块中,就像results='hold'.

到目前为止,唯一能模拟我想要的选项是选项collapse=T,但这将输出和代码粘在一起,这是我不想要的。

这段代码说明了这种情况:

---
title: "Example"
author: "Me"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```



```{r}
a <- function(){
  print("hello")
  print("world")
  message("hello again")
  message("world")
}
```

### default
```{r}
a()
```


### with `results='hold'`
```{r results='hold'}
a()
```


### with `collapse=T`
```{r collapse=T}
a()
```
Run Code Online (Sandbox Code Playgroud)

输出 : rmd

我还认为有趣的是如何在结果/打印之前输出消息results='hold'

Mat*_*lke 1

这是一个不同的版本,可能更适合OP的需求。

此版本会将消息和输出混合在一起,就像将消息发送到控制台时观察到的那样。

这是通过覆盖三个钩子来完成的:messageoutputchunk

Rmd 的内容

---
title: "Knitr As Console Output Hook Implementation"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)

# global store for output and messages
asconsole_output <- NULL

# override message hook
# if output option is 'asconsole', append message to global
# otherwise let knitr do its thing
knitr::knit_hooks$set(message = function(x, options) {
  if(!is.null(options$output)) {
    if(options$output == 'asconsole') {
      asconsole_output <<- c(asconsole_output, x)
      return(NULL)
    }
  }
  
  knitr::hooks_html()$message(x, options)
})
  
# override output hook
# if output option is 'asconsole', append output to global
# otherwise let knitr do its thing
knitr::knit_hooks$set(output = function(x, options) {
  if(!is.null(options$output)) {
    if(options$output == 'asconsole') {
      asconsole_output <<- c(asconsole_output, x)
      return(NULL)
    }
  }
  
  knitr::hooks_html()$output(x, options)
})

# override chunk hook
# if output option is 'asconsole', clear global and append formatted contents
# otherwise let knitr do its thing
knitr::knit_hooks$set(chunk = function(x, options) {
  if(!is.null(options$output)) {
    if(options$output == 'asconsole') {
      y <- paste(asconsole_output, collapse = "")
      y <- knitr::hooks_html()$output(y, options)
      asconsole_output <<- NULL
      y <- paste(x, y, collapse = "")
      return(y)
    }
  }
  
  knitr::hooks_html()$chunk(x, options)
})

# test function with results and messages
a <- function() {
  print("a out 1")
  message("a msg 1")
  print("a out 2")
  message("a msg 2")
}
```

# Default Behavior

```{r}
a()
```

# Output As Console

```{r, output='asconsole'}
a()
```
Run Code Online (Sandbox Code Playgroud)

输出 HTML

在此输入图像描述