Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 RMarkdown ? By the same way we can display `t 2+2`, but replacing t with r executes the R code 2+2.

The only way I have found so far is:

<p><code  class="r">`</code><code class="r">r 2+2`</code></p> 

Not very convenient. Maybe I should define a new css for doing that more conveniently ?

like image 274
Stéphane Laurent Avatar asked Dec 05 '13 19:12

Stéphane Laurent


People also ask

How do I embed an R code in Markdown?

To insert a code chunk, press Ctrl + Alt + I in the source pane (top left pane in the default settings of RStudio). A code chunk will appear: Inside the code chunk you can write and run R-code.

How do I show code chunk in R markdown?

You can open it here in RStudio Cloud. or by typing the chunk delimiters ```{r} and ``` . When you render your . Rmd file, R Markdown will run each code chunk and embed the results beneath the code chunk in your final report.

What is verbatim code?

Verbatim coding is a technique used in market research, consisting of the assignment of numeric codes to various words, phrases, ideas, sounds or pictures in order to permit the extraction and quantitative analysis of information and meaning.

How do I display Markdown in R?

To open a new file, click File > New File > R Markdown in the RStudio menu bar. A window will pop up that helps you build the YAML frontmatter for the . Rmd file. Use the radio buttons to select the specific type of output that you wish to build.


2 Answers

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.

like image 140
Yihui Xie Avatar answered Sep 24 '22 06:09

Yihui Xie


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.

like image 42
adunaic Avatar answered Sep 22 '22 06:09

adunaic