How to display verbatim inline r code with backticks using Rmarkdown?

后端 未结 5 512
广开言路
广开言路 2020-12-08 19:49

By doubling the backticks in Markdown, it is easy to render some text in code style including the backticks, such as: `r 2+2`. But how to do that with RMark

相关标签:
5条回答
  • 2020-12-08 20:12

    Here is a satisfactory finding. First define the function

    rinline <- function(code){
      html <- '<code  class="r">``` `r CODE` ```</code>'
      sub("CODE", code, html)
    }
    

    in an invisible chunk. Then you can show `r 2+2` by typing:

    Some R code inline : `r rinline("2+2")` - nice 
    
    0 讨论(0)
  • 2020-12-08 20:20

    Here is a trick that I use. First, note \x60 is `:

    > cat('\x60', '\n')
    ` 
    

    Then you write

    `r '\x60r foo+bar\x60'`
    

    which will give you `r foo+bar` in the markdown output, but that will become r foo+bar in the HTML output, so you need to protect the backticks in markdown, using two (or more) backticks. Then you end up with this hairball:

    `` `r '\x60r foo+bar\x60'` ``
    

    Your own solution is good, but I'd just define

    rinline <- function(code) {
      sprintf('``` `r %s` ```', code)
    }
    

    Also see this post for another trick.

    0 讨论(0)
  • 2020-12-08 20:20

    I just learnt about the results='asis' option.
    So, yet another way; for fun and learning :-)

    ```{r, results='asis', echo=FALSE}
    cat("`` `r 2+2` ``")
    ```
    
    0 讨论(0)
  • 2020-12-08 20:22

    To anyone looking at this now, you may want to check out the more recent solution here: embed Rmarkdown without knitr evaluation

    Essentially you can do:

    Some R code inline : `r knitr::inline_expr("2+2")`
    

    I'm guessing that the functionality describe above has been added to knitr directly but it saves us defining the function ourselves.

    0 讨论(0)
  • 2020-12-08 20:27

    The solution of Yihui Xie was not displaying the enclosing quotations in the inserted code when rendering a README.md file for a Github repository. In that case I used html code:

    <code>&grave;r foo(x)&grave;</code>
    

    Which displays `r foo(x)` inline.

    0 讨论(0)
提交回复
热议问题