Show an R markdown chunk in the final output

前端 未结 3 1946
余生分开走
余生分开走 2020-12-19 20:46

I am writing on a presentation using Knitr, Markdown and Slidify. The slides will be partly deal with Knitr as topic which is the reason why I stumbeld upon a problem. I ca

3条回答
  •  南方客
    南方客 (楼主)
    2020-12-19 21:38

    Here is another solution that makes use of chunk hooks. The idea is that if you have a chunk with option verbatim = TRUE, it activates the hook and outputs the chunk verbatim. I have checked that it works with Slidify too.

    ```{r echo = FALSE}
    require(knitr)
    hook_source_def = knit_hooks$get('source')
    knit_hooks$set(source = function(x, options){
      if (!is.null(options$verbatim) && options$verbatim){
        opts = gsub(",\\s*verbatim\\s*=\\s*TRUE\\s*", "", options$params.src)
        bef = sprintf('\n\n    ```{r %s}\n', opts, "\n")
        stringr::str_c(bef, paste(knitr:::indent_block(x, "    "), collapse = '\n'), "\n    ```\n")
      } else {
         hook_source_def(x, options)
      }
    })
    ```
    
    ```{r verbatimchunk, verbatim = TRUE}
    x = 1 + 1
    x
    ```
    
    ```{r regularchunk}
    x = 1 + 1
    x
    ```
    

    EDIT: The trick with code chunks after a list is that the list environment needs to be broken. A quick and dirty way is just to add an empty paragraph element. Alternately, you can fix the hook so that en empty paragraph is automatically added at the beginning of the code chunk.

    * element 1
    * element 2
    
    

    ```{r verbatimchunk_3, verbatim = TRUE} x = 1 + 1 x ```

提交回复
热议问题