• 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 GitHub 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
    • 2.10 VS Code
      • 2.10.1 languageserver package
      • 2.10.2 Radian
      • 2.10.3 FAQ
      • 2.10.4 Plot Viewer
      • 2.10.5 Work with Rmd
  • 3 Rmd
    • 3.1 YAML metadata
      • 3.1.1 Top-level YAML metadata
      • 3.1.2 MathJax Options
      • 3.1.3 Document dependency
    • 3.2 Render Rmd
      • 3.2.1 Render a single document
      • 3.2.2 Render multiple documents as a website
    • 3.3 Chunk Options
      • Hooks
    • 3.4 Print Verbatim R code chunks
    • 3.5 Rmd Basics
    • 3.6 Citations
      • 3.6.1 Bibliographies
      • 3.6.2 Bibliography placement
    • 3.7 Cross References
      • 3.7.1 Using bookdown
      • 3.7.2 Using the LaTeX Way
    • 3.8 Equations
    • 3.9 Theorems
    • 3.10 Figures
      • Latex symbols in Fig. caption
      • Refer to another figure in figure caption
    • 3.11 Tables
      • 3.11.1 knitr::kable
      • 3.11.2 Data frame printing
      • 3.11.3 Stargazer
      • 3.11.4 xtable
      • 3.11.5 kableExtra
    • 3.12 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.2.1 Rendering bookdown website
      • 4.2.2 Rendering bookdown book
    • 4.3 Toggle Visibility of Solutions
    • 4.4 Quarto
      • 4.4.1 Book Structure
      • 4.4.2 HTML Theming
      • 4.4.3 Render Quarto
      • 4.4.4 Cross References
      • 4.4.5 Equations
      • 4.4.6 Divs and Spans
      • 4.4.7 Theorems
      • 4.4.8 Callouts
  • 5 Basic R
    • 5.1 Data Input & Output
      • 5.1.1 Read Data
      • 5.1.2 Write Data
    • 5.2 Functions
      • 5.2.1 Inspecting Object Types and Structure
      • 5.2.2 Type of Variables
      • 5.2.3 Variable Scope
      • 5.2.4 Control Structures
    • 5.3 Basic R functions
      • 5.3.1 Workspace Management
      • 5.3.2 Data Display and Output
      • 5.3.3 Data Manipulation and Transformation
      • 5.3.4 Generate Random Seeds
      • 5.3.5 Draw random samples
      • 5.3.6 Fit a distribution
      • 5.3.7 Operation on list
    • 5.4 Data Splitting and Grouping
      • 5.4.1 The split() Function
      • 5.4.2 Split-and-Apply Operations
    • 5.5 *apply() Family
      • 5.5.1 Parallel version of apply function
      • 5.5.2 Related Functions
    • 5.6 Statistical Summary Functions
    • 5.7 Contingency Table
      • 5.7.1 Basic Frequency Counting
      • 5.7.2 Creating Contingency Tables
      • 5.7.3 Working with Arrays and Multi-dimensional Tables
      • 5.7.4 Flattening and Exporting Tables
      • 5.7.5 Table Visualization and Formatting
    • 5.8 Data Frame Operations
      • Column/Row-wise Operations
      • 5.8.1 Process NA values
    • 5.9 Matrix multiplication
    • 5.10 String Operations
  • 6 Tidyverse
    • 6.1 Basic operations on tibbles
      • 6.1.1 Check Unique Values
      • 6.1.2 Column Names
      • 6.1.3 Column Operations
      • 6.1.4 mutate
      • 6.1.5 Concatenate rows into a tibble
      • 6.1.6 Data Subsetting
      • 6.1.7 Dynamic Selection
      • 6.1.8 Merge
    • 6.2 Pipe Operator
      • 6.2.1 Native Pipe |>
    • 6.3 Categorical Variables
      • 6.3.1 Manipulate String Columns
      • 6.3.2 Factors
    • 6.4 Group and Apply Functions
      • 6.4.1 group_by()
      • 6.4.2 Subset rows
      • 6.4.3 Summarize
      • 6.4.4 split-apply-combine
      • 6.4.5 dplyr::group_modify()
  • 7 Graphics
    • 7.1 Multipanel Plot
      • 7.1.1 With Base R
      • 7.1.2 With cowplot package
    • 7.2 Goodlooking Colors
      • 7.2.1 Color models
      • 7.2.2 Base R functions to specify colors
      • 7.2.3 colorspace Package
      • 7.2.4 RColorBrewer
      • 7.2.5 Grey Scale
      • 7.2.6 ggsci
      • 7.2.7 viridis
      • 7.2.8 Generate Color Palettes
      • 7.2.9 Color Interpolation
    • 7.3 Math Expression in Figures
    • 7.4 Control Graphics Devices
      • 7.4.1 Save PNG
    • 7.5 ggplot
      • 7.5.1 Wide table to Long table
      • 7.5.2 Dual y-axis plot
      • 7.5.3 aes()
      • 7.5.4 Add regression line
      • 7.5.5 Subplots
      • 7.5.6 Parameters
      • 7.5.7 guides(), together with guide_legend()
      • 7.5.8 Template for multi-series
      • 7.5.9 grid.gedit()
    • 7.6 plot Raster data
      • 7.6.1 Add Patterns to Shapes
    • 7.7 Histogram
    • 7.8 QQ-plot
    • 7.9 Heatmap
  • 8 Time Series
    • 8.1 Date
    • 8.2 Process Data
      • 8.2.1 tidyquant
      • 8.2.2 From tibble to xts
    • 8.3 Portfolio Return
    • 8.4 Plot TS
      • 8.4.1 plot.xts
      • 8.4.2 autoplot
    • 8.5 Time Series Regression
      • 8.5.1 Lag Polynomial
  • 9 Regression
    • 9.1 OLS
      • 9.1.1 Get the coef estimates
      • 9.1.2 Covariance Matrix
      • 9.1.3 Model performance
      • 9.1.4 Model Summary
      • 9.1.5 Dummy variable
    • 9.2 Panel
      • 9.2.1 Dynamic Panel
  • 10 Machine Learning
    • 10.1 Imbalanced datasets
      • 10.1.1 Downsampling and Upweighting
    • 10.2 Random Forest
      • Implementation in R
      • Imbalance Classification
    • 10.3 Neural Network
  • 11 Stata
    • 11.1 Basic syntax
      • 11.1.1 System Variables
      • 11.1.2 Matrix
      • 11.1.3 Factor Variables
      • 11.1.4 Time series varlists
      • 11.1.5 Labels
    • 11.2 Data Manipulation
      • 11.2.1 Import and Export
      • 11.2.2 Save Estimation Results
      • 11.2.3 Stored Results
    • 11.3 Predict
    • 11.4 Forecast
      • Add equations/identifies
      • Solve the foreceast
      • Use example: forecast a panel
    • 11.5 Panel
    • 11.6 Arellano-Bond Estimator
      • 11.6.1 xtabond2
  • Published with bookdown

R Notes

3.4 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