Show an R markdown chunk in the final output

前端 未结 3 1938
余生分开走
余生分开走 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:17

    I think you need to add an empty string after ```{r}, and knitr will not execute the chunk, but will display it. See the example here

    This on a slide works for me (where the top one executes and the bottom does not)

    ---
    
    ```{r}
    list(5, 6, 7)
    ```
    
    
        ```{r}`r ''`
        hist(rnorm(100))
        5 + 6
        ```
    
    ---
    
    0 讨论(0)
  • 2020-12-19 21:26

    Very late to the party, but this also seems to work:

    ```{r echo=FALSE, class.output="r", comment=""}
    cat("```{r}\nx <- 1 + 1\nx\n```")
    ```
    

    Or, equivalent but perhaps nicer to read and write:

    ```{r echo=FALSE, class.output="r", comment=""}
    cat(paste(sep = "\n",
      "```{r}",
      "x <- 1 + 1",
      "x",
      "```"
    ))
    ```
    
    0 讨论(0)
  • 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
    
    <p></p>
    ```{r verbatimchunk_3, verbatim = TRUE}
    x = 1 + 1
    x
    ```
    
    0 讨论(0)
提交回复
热议问题