• R Notes
  • 1 About
    • 1.1 Usage
    • 1.2 Render book
    • 1.3 Preview book
  • 2 Rstudio
    • 2.1 Dark Theme
    • 2.2 Update R
    • 2.3 Packages Management
      • 2.3.1 Load packages
      • 2.3.2 Install packages
      • 2.3.3 Update packages
      • 2.3.4 Put your R package on GitHub
    • 2.4 Using Git with RStudio
    • 2.5 Copilot
    • 2.6 Save R Workspace
    • 2.7 Pane Layout
    • 2.8 Options
    • 2.9 R Startup
      • 2.9.1 .Rprofile
      • 2.9.2 .Renviron
  • 3 Rmd
    • 3.1 YAML metadata
      • 3.1.1 Render Rmd
      • 3.1.2 Document dependency
    • 3.2 Chunk Options
      • Hooks
    • 3.3 Print Verbatim R code chunks
    • 3.4 Rmd Basics
    • 3.5 Citations
      • 3.5.1 Bibliographies
      • 3.5.2 Bibliography placement
    • 3.6 Cross References
      • 3.6.1 Using bookdown
      • 3.6.2 Using the LaTeX Way
    • 3.7 Equations
    • 3.8 Theorems
    • 3.9 Figures
      • Latex symbols in Fig. caption
      • Refer to another figure in figure caption
    • 3.10 Tables
      • 3.10.1 knitr::kable
      • 3.10.2 Data frame printing
      • 3.10.3 Stargazer
      • 3.10.4 kableExtra
    • 3.11 Rmd GitHub Pages
      • Project structure
      • _site.yml config
      • index.Rmd
      • R scripts
      • Workflow
      • CSS Style
  • 4 bookdown
    • 4.1 bookdown project structure
      • _output.yml
      • _bookdown.yml
      • index.Rmd
      • .Rmd files
    • 4.2 Rendering bookdown
    • 4.3 Toggle Visibility of Solutions
    • 4.4 Quarto
      • 4.4.1 Book Structure
      • 4.4.2 HTML Theming
      • 4.4.3 Cross References
      • 4.4.4 Equations
      • 4.4.5 Theorems
  • 5 Basic R
    • 5.1 Data Input & Output
      • 5.1.1 Read Data
      • 5.1.2 Write Data
  • 6 Regression
  • 7 Machine Learning
    • 7.1 Imbalanced datasets
      • 7.1.1 Downsampling and Upweighting
    • 7.2 Random Forest
      • Implementation in R
      • Imbalance Classification
    • 7.3 Neural Network
  • Published with bookdown

R Notes

3.3 Print Verbatim R code chunks

verbatim in line code

  • use knitr::inline_expr.
---
title: "Test inline expr"
output: html_document
---

To use `chunk_reveal("walrus", title = "## Walrus operator")` inline, you can wrap it in R inline chunk like this `` `r chunk_reveal("walrus", title = "## Walrus operator")` ``

Including verbatim R code chunks inside R Markdown

One solution for including verbatim R code chunks (see below for more) is to insert hidden inline R code (`r ''`) immediately before or after your R code chunk.

  • The hidden inline R code will be evaluated as an inline expression to an empty string by knitr.

Then wrap the whole block within a markdown code block. The rendered output will display the verbatim R code chunk — including backticks.

R code generating the four backticks block:

output_code <-
"````markdown
```{r}
plot(cars)
``` \n````"
cat(output_code)

Write this code in your R Markdown document:

output_code <-
"````markdown
`r ''````{r}
plot(cars)
``` \n````"
cat(output_code)
````markdown
`r ''````{r}
plot(cars)
``` 
````

or

output_code <-
"````markdown
```{r}`r ''`
plot(cars)
``` \n````"
cat(output_code)
````markdown
```{r}`r ''`
plot(cars)
``` 
````

Knit the document and the code will render like this in your output:

```{r}
plot(cars)
```

This method makes use of Markdown Syntax for code.

Q: What is the Markdown Syntax for code?
A:

  • Inline code use a pair of backticks, e.g., `code`. To use \(n\) literal backticks, use at least \(n+1\) backticks outside. Note that use a space to separate your outside backticks from your literal backtick(s). For example, to generate `code`, you use ``␣`code`␣`` (i.e., two backticks + space + one backtick + code + one backtick + space + two backticks). Note that you need to write sequentially.

  • Plain code blocks can be written either

    • After three or more backticks (fenced code blocks), or

      Can also use tildes (~)

    • Indent the blocks by four spaces (indented code blocks)

      Special characters do not trigger special formatting, and all spaces and line breaks are preserved. Blank lines in the verbatim text need not begin with four spaces.

  • Note that code blocks must be separated from surrounding text by blank lines.

If the code itself contains a row of tildes or backticks, just use a longer row of tildes or backticks at the start and end:

~~~~~~~~~~~~~~~~
~~~~~~~~~~
code including tildes
~~~~~~~~~~
~~~~~~~~~~~~~~~~

These begin with a row of three or more tildes (~) and end with a row of tildes that must be at least as long as the starting row.

A trick if you don’t want to type more than three tildes or backticks is that you just use different inner and outer symbols.

~~~markdown
```r
print ("hello world")
```
~~~

Will be rendered as:

```r
print ("hello world")
```

A shortcut form (without braces) can also be used for specifying the language of the code block:

```haskell
qsort [] = []
```

This is equivalent to:

``` {.haskell}
qsort [] = []
```

haskell is the language class.

You can add more classes, such as numberLines for adding line numbers.

This shortcut form may be combined with attributes:

```haskell {.numberLines}
qsort [] = []
```

Which is equivalent to:

``` {.haskell .numberLines}
qsort [] = []
```

and

<pre id="mycode" class="haskell numberLines" startFrom="100">
  <code>
  primes = filterPrime [2..] where
  filterPrime (p:xs) =
    p : filterPrime [x | x <- xs, x `mod` p /= 0]
  </code>
</pre>  

If highlighting is supported for your output format and language, then the code block above will appear highlighted, with numbered lines starting with 100, 101, and go on.

  
  primes = filterPrime [2..] where
  filterPrime (p:xs) =
    p : filterPrime [x | x <- xs, x `mod` p /= 0]
  

Code chunks within enumerate

  • Mind the indentation. Rstudio does not automatically adjust indentation for codes.

  • specify results="asis" if encounter

    You can’t use `macro parameter character #’ in horizontal mode.

  • cross references using bookdown (\@ref{fig:scatter-plot}) might not work.

    Use latex references \ref{fig:scatter-plot} (base latex) or \autoref{fig:scatter-plot} (from hyperref package)

  • markdown language does not work well inside latex environments. A possible workaround is use 1 and indent four spaces for contents that follow.

If it is still a pain in the ass, use this solution.

Basically, just copy the output from R condole and paste in Rmd.


References:

https://yihui.org/en/2017/11/knitr-verbatim-code-chunk/

https://support.posit.co/hc/en-us/articles/360018181633-Including-verbatim-R-code-chunks-inside-R-Markdown

https://themockup.blog/posts/2021-08-27-displaying-verbatim-code-chunks-in-xaringan-presentations/

Pandoc’s Markdown: https://pandoc.org/MANUAL.html#fenced-code-blocks