2.6 R Code Chunks And Inline R Code | R Markdown - Bookdown
Maybe your like
- R Markdown: The Definitive Guide
- Preface
- How to read this book
- Structure of the book
- Software information and conventions
- Acknowledgments
- About the Authors
- Yihui Xie
- J.J. Allaire
- Garrett Grolemund
- I Get Started
- 1 Installation
- 2 Basics
- 2.1 Example applications
- 2.1.1 Airbnb’s knowledge repository
- 2.1.2 Homework assignments on RPubs
- 2.1.3 Personalized mail
- 2.1.4 2017 Employer Health Benefits Survey
- 2.1.5 Journal articles
- 2.1.6 Dashboards at eelloo
- 2.1.7 Books
- 2.1.8 Websites
- 2.2 Compile an R Markdown document
- 2.3 Cheat sheets
- 2.4 Output formats
- 2.5 Markdown syntax
- 2.5.1 Inline formatting
- 2.5.2 Block-level elements
- 2.5.3 Math expressions
- 2.6 R code chunks and inline R code
- 2.6.1 Figures
- 2.6.2 Tables
- 2.7 Other language engines
- 2.7.1 Python
- 2.7.2 Shell scripts
- 2.7.3 SQL
- 2.7.4 Rcpp
- 2.7.5 Stan
- 2.7.6 JavaScript and CSS
- 2.7.7 Julia
- 2.7.8 C and Fortran
- 2.8 Interactive documents
- 2.8.1 HTML widgets
- 2.8.2 Shiny documents
- 2.1 Example applications
- II Output Formats
- 3 Documents
- 3.1 HTML document
- 3.1.1 Table of contents
- 3.1.2 Section numbering
- 3.1.3 Tabbed sections
- 3.1.4 Appearance and style
- 3.1.5 Figure options
- 3.1.6 Data frame printing
- 3.1.7 Code folding
- 3.1.8 MathJax equations
- 3.1.9 Document dependencies
- 3.1.10 Advanced customization
- 3.1.11 Shared options
- 3.1.12 HTML fragments
- 3.2 Notebook
- 3.2.1 Using Notebooks
- 3.2.2 Saving and sharing
- 3.2.3 Notebook format
- 3.3 PDF document
- 3.3.1 Table of contents
- 3.3.2 Figure options
- 3.3.3 Data frame printing
- 3.3.4 Syntax highlighting
- 3.3.5 LaTeX options
- 3.3.6 LaTeX packages for citations
- 3.3.7 Advanced customization
- 3.3.8 Other features
- 3.4 Word document
- 3.4.1 Other features
- 3.5 OpenDocument Text document
- 3.5.1 Other features
- 3.6 Rich Text Format document
- 3.6.1 Other features
- 3.7 Markdown document
- 3.7.1 Markdown variants
- 3.7.2 Other features
- 3.8 R package vignette
- 3.1 HTML document
- 4 Presentations
- 4.1 ioslides presentation
- 4.1.1 Display modes
- 4.1.2 Incremental bullets
- 4.1.3 Visual appearance
- 4.1.4 Code highlighting
- 4.1.5 Adding a logo
- 4.1.6 Tables
- 4.1.7 Advanced layout
- 4.1.8 Text color
- 4.1.9 Presenter mode
- 4.1.10 Printing and PDF output
- 4.1.11 Custom templates
- 4.1.12 Other features
- 4.2 Slidy presentation
- 4.2.1 Display modes
- 4.2.2 Text size
- 4.2.3 Footer elements
- 4.2.4 Other features
- 4.3 Beamer presentation
- 4.3.1 Themes
- 4.3.2 Slide level
- 4.3.3 Other features
- 4.4 PowerPoint presentation
- 4.4.1 Custom templates
- 4.4.2 Other features
- 4.1 ioslides presentation
- III Extensions
- 5 Dashboards
- 5.1 Layout
- 5.1.1 Row-based layouts
- 5.1.2 Attributes on sections
- 5.1.3 Multiple pages
- 5.1.4 Story boards
- 5.2 Components
- 5.2.1 Value boxes
- 5.2.2 Gauges
- 5.2.3 Text annotations
- 5.2.4 Navigation bar
- 5.3 Shiny
- 5.3.1 Getting started
- 5.3.2 A Shiny dashboard example
- 5.3.3 Input sidebar
- 5.3.4 Learning more
- 5.1 Layout
- 6 Tufte Handouts
- 6.1 Headings
- 6.2 Figures
- 6.2.1 Margin figures
- 6.2.2 Arbitrary margin content
- 6.2.3 Full-width figures
- 6.2.4 Main column figures
- 6.3 Sidenotes
- 6.4 References
- 6.5 Tables
- 6.6 Block quotes
- 6.7 Responsiveness
- 6.8 Sans-serif fonts and epigraphs
- 6.9 Customize CSS styles
- 7 xaringan Presentations
- 7.1 Get started
- 7.2 Keyboard shortcuts
- 7.3 Slide formatting
- 7.3.1 Slides and properties
- 7.3.2 The title slide
- 7.3.3 Content classes
- 7.3.4 Incremental slides
- 7.3.5 Presenter notes
- 7.3.6 yolo: true
- 7.4 Build and preview slides
- 7.5 CSS and themes
- 7.6 Some tips
- 7.6.1 Autoplay slides
- 7.6.2 Countdown timer
- 7.6.3 Highlight code lines
- 7.6.4 Working offline
- 7.6.5 Macros
- 7.6.6 Disadvantages
- 8 reveal.js Presentations
- 8.1 Display modes
- 8.2 Appearance and style
- 8.2.1 Smaller text
- 8.3 Slide transitions
- 8.4 Slide backgrounds
- 8.5 2-D presentations
- 8.6 Custom CSS
- 8.6.1 Slide IDs and classes
- 8.6.2 Styling text spans
- 8.7 reveal.js options
- 8.8 reveal.js plugins
- 8.9 Other features
- 9 Community Formats
- 9.1 Lightweight Pretty HTML Documents
- 9.1.1 Usage
- 9.1.2 Package vignettes
- 9.2 The rmdformats package
- 9.3 Shower presentations
- 9.1 Lightweight Pretty HTML Documents
- 10 Websites
- 10.1 Get started
- 10.2 The directory structure
- 10.3 Deployment
- 10.4 Other site generators
- 10.5 rmarkdown’s site generator
- 10.5.1 A simple example
- 10.5.2 Site authoring
- 10.5.3 Common elements
- 10.5.4 Site navigation
- 10.5.5 HTML generation
- 10.5.6 Site configuration
- 10.5.7 Publishing websites
- 10.5.8 Additional examples
- 10.5.9 Custom site generators
- 11 HTML Documentation for R Packages
- 11.1 Get started
- 11.2 Components
- 11.2.1 Home page
- 11.2.2 Function reference
- 11.2.3 Articles
- 11.2.4 News
- 11.2.5 Navigation bar
- 12 Books
- 12.1 Get started
- 12.2 Project structure
- 12.2.1 Index file
- 12.2.2 Rmd files
- 12.2.3 _bookdown.yml
- 12.2.4 _output.yml
- 12.3 Markdown extensions
- 12.3.1 Number and reference equations
- 12.3.2 Theorems and proofs
- 12.3.3 Special headers
- 12.3.4 Text references
- 12.3.5 Cross referencing
- 12.4 Output Formats
- 12.4.1 HTML
- 12.4.2 LaTeX/PDF
- 12.4.3 E-books
- 12.4.4 A single document
- 12.5 Editing
- 12.5.1 Build the book
- 12.5.2 Preview a chapter
- 12.5.3 Serve the book
- 12.5.4 RStudio addins
- 12.6 Publishing
- 12.6.1 RStudio Connect
- 12.6.2 Other services
- 12.6.3 Publishers
- 13 Journals
- 13.1 Get started
- 13.2 rticles templates
- 13.3 Using a template
- 13.4 LaTeX content
- 13.5 Linking with bookdown
- 13.6 Contributing templates
- 14 Interactive Tutorials
- 14.1 Get started
- 14.2 Tutorial types
- 14.3 Exercises
- 14.3.1 Solutions
- 14.3.2 Hints
- 14.4 Quiz questions
- 14.5 Videos
- 14.6 Shiny components
- 14.7 Navigation and progress tracking
- IV Other Topics
- 15 Parameterized reports
- 15.1 Declaring parameters
- 15.2 Using parameters
- 15.3 Knitting with parameters
- 15.3.1 The Knit button
- 15.3.2 Knit with custom parameters
- 15.3.3 The interactive user interface
- 15.4 Publishing
- 16 HTML Widgets
- 16.1 Overview
- 16.2 A widget example (sigma.js)
- 16.2.1 File layout
- 16.2.2 Dependencies
- 16.2.3 R binding
- 16.2.4 JavaScript binding
- 16.2.5 Demo
- 16.3 Creating your own widgets
- 16.3.1 Requirements
- 16.3.2 Scaffolding
- 16.3.3 Other packages
- 16.4 Widget sizing
- 16.4.1 Specifying a sizing policy
- 16.4.2 JavaScript resize method
- 16.5 Advanced topics
- 16.5.1 Data transformation
- 16.5.2 Passing JavaScript functions
- 16.5.3 Custom widget HTML
- 16.5.4 Create a widget without an R package
- 17 Document Templates
- 17.1 Template structure
- 17.2 Supporting files
- 17.3 Custom Pandoc templates
- 17.4 Sharing your templates
- 18 Creating New Formats
- 18.1 Deriving from built-in formats
- 18.2 Fully custom formats
- 18.3 Using a new format
- 19 Shiny Documents
- 19.1 Getting started
- 19.2 Deployment
- 19.2.1 ShinyApps.io
- 19.2.2 Shiny Server / RStudio Connect
- 19.3 Embedded Shiny apps
- 19.3.1 Inline applications
- 19.3.2 External applications
- 19.4 Shiny widgets
- 19.4.1 The shinyApp() function
- 19.4.2 Example: k-Means clustering
- 19.4.3 Widget size and layout
- 19.5 Multiple pages
- 19.6 Delayed rendering
- 19.7 Output arguments for render functions
- 19.7.1 A caveat
- References
- Published with bookdown
2.6 R code chunks and inline R code
You can insert an R code chunk either using the RStudio toolbar (the Insert button) or the keyboard shortcut Ctrl + Alt + I (Cmd + Option + I on macOS).
There are a lot of things you can do in a code chunk: you can produce text output, tables, or graphics. You have fine control over all these output via chunk options, which can be provided inside the curly braces (between ```{r and }). For example, you can choose hide text output via the chunk option results = 'hide', or set the figure height to 4 inches via fig.height = 4. Chunk options are separated by commas, e.g.,
```{r, chunk-label, results='hide', fig.height=4}The value of a chunk option can be an arbitrary R expression, which makes chunk options extremely flexible. For example, the chunk option eval controls whether to evaluate (execute) a code chunk, and you may conditionally evaluate a chunk via a variable defined previously, e.g.,
```{r} # execute code if the date is later than a specified day do_it = Sys.Date() > '2018-02-14' ``` ```{r, eval=do_it} x = rnorm(100) ```There are a large number of chunk options in knitr documented at https://yihui.name/knitr/options. We list a subset of them below:
eval: Whether to evaluate a code chunk.
echo: Whether to echo the source code in the output document (someone may not prefer reading your smart source code but only results).
results: When set to 'hide', text output will be hidden; when set to 'asis', text output is written “as-is,” e.g., you can write out raw Markdown text from R code (like cat('**Markdown** is cool.\n')). By default, text output will be wrapped in verbatim elements (typically plain code blocks).
collapse: Whether to merge text output and source code into a single code block in the output. This is mostly cosmetic: collapse = TRUE makes the output more compact, since the R source code and its text output are displayed in a single output block. The default collapse = FALSE means R expressions and their text output are separated into different blocks.
warning, message, and error: Whether to show warnings, messages, and errors in the output document. Note that if you set error = FALSE, rmarkdown::render() will halt on error in a code chunk, and the error will be displayed in the R console. Similarly, when warning = FALSE or message = FALSE, these messages will be shown in the R console.
include: Whether to include anything from a code chunk in the output document. When include = FALSE, this whole code chunk is excluded in the output, but note that it will still be evaluated if eval = TRUE. When you are trying to set echo = FALSE, results = 'hide', warning = FALSE, and message = FALSE, chances are you simply mean a single option include = FALSE instead of suppressing different types of text output individually.
cache: Whether to enable caching. If caching is enabled, the same code chunk will not be evaluated the next time the document is compiled (if the code chunk was not modified), which can save you time. However, I want to honestly remind you of the two hard problems in computer science (via Phil Karlton): naming things, and cache invalidation. Caching can be handy but also tricky sometimes.
fig.width and fig.height: The (graphical device) size of R plots in inches. R plots in code chunks are first recorded via a graphical device in knitr, and then written out to files. You can also specify the two options together in a single chunk option fig.dim, e.g., fig.dim = c(6, 4) means fig.width = 6 and fig.height = 4.
out.width and out.height: The output size of R plots in the output document. These options may scale images. You can use percentages, e.g., out.width = '80%' means 80% of the page width.
fig.align: The alignment of plots. It can be 'left', 'center', or 'right'.
dev: The graphical device to record R plots. Typically it is 'pdf' for LaTeX output, and 'png' for HTML output, but you can certainly use other devices, such as 'svg' or 'jpeg'.
fig.cap: The figure caption.
child: You can include a child document in the main document. This option takes a path to an external file.
Chunk options in knitr can be surprisingly powerful. For example, you can create animations from a series of plots in a code chunk. I will not explain how here because it requires an external software package, but encourage you to read the documentation carefully to discover the possibilities. You may also read Xie (2015), which is a comprehensive guide to the knitr package, but unfortunately biased towards LaTeX users for historical reasons (which was one of the reasons why I wanted to write this R Markdown book).
There is an optional chunk option that does not take any value, which is the chunk label. It should be the first option in the chunk header. Chunk labels are mainly used in filenames of plots and cache. If the label of a chunk is missing, a default one of the form unnamed-chunk-i will be generated, where i is incremental. I strongly recommend that you only use alphanumeric characters (a-z, A-Z and 0-9) and dashes (-) in labels, because they are not special characters and will surely work for all output formats. Other characters, spaces and underscores in particular, may cause trouble in certain packages, such as bookdown.
If a certain option needs to be frequently set to a value in multiple code chunks, you can consider setting it globally in the first code chunk of your document, e.g.,
```{r, setup, include=FALSE} knitr::opts_chunk$set(fig.width = 8, collapse = TRUE) ```Besides code chunks, you can also insert values of R objects inline in text. For example:
```{r} x = 5 # radius of a circle ``` For a circle with the radius `r x`, its area is `r pi * x^2`.2.6.1 Figures
By default, figures produced by R code will be placed immediately after the code chunk they were generated from. For example:
```{r} plot(cars, pch = 18) ```You can provide a figure caption using fig.cap in the chunk options. If the document output format supports the option fig_caption: true (e.g., the output format rmarkdown::html_document), the R plots will be placed into figure environments. In the case of PDF output, such figures will be automatically numbered. If you also want to number figures in other formats (such as HTML), please see the bookdown package in Chapter 12 (in particular, see Section 12.4.4).
PDF documents are generated through the LaTeX files generated from R Markdown. A highly surprising fact to LaTeX beginners is that figures float by default: even if you generate a plot in a code chunk on the first page, the whole figure environment may float to the next page. This is just how LaTeX works by default. It has a tendency to float figures to the top or bottom of pages. Although it can be annoying and distracting, we recommend that you refrain from playing the “Whac-A-Mole” game in the beginning of your writing, i.e., desparately trying to position figures “correctly” while they seem to be always dodging you. You may wish to fine-tune the positions once the content is complete using the fig.pos chunk option (e.g., fig.pos = 'h'). See https://www.overleaf.com/learn/latex/Positioning_images_and_tables for possible values of fig.pos and more general tips about this behavior in LaTeX. In short, this can be a difficult problem for PDF output.
To place multiple figures side-by-side from the same code chunk, you can use the fig.show='hold' option along with the out.width option. Figure 2.5 shows an example with two plots, each with a width of 50%.
par(mar = c(4, 4, .2, .1)) plot(cars, pch = 19) plot(pressure, pch = 17)
FIGURE 2.5: Two plots side-by-side.
If you want to include a graphic that is not generated from R code, you may use the knitr::include_graphics() function, which gives you more control over the attributes of the image than the Markdown syntax of  (e.g., you can specify the image width via out.width). Figure 2.6 provides an example of this.
```{r, out.width='25%', fig.align='center', fig.cap='...'} knitr::include_graphics('images/hex-rmarkdown.png') ```
FIGURE 2.6: The R Markdown hex logo.
2.6.2 Tables
The easiest way to include tables is by using knitr::kable(), which can create tables for HTML, PDF and Word outputs.3 Table captions can be included by passing caption to the function, e.g.,
```{r tables-mtcars} knitr::kable(iris[1:5, ], caption = 'A caption') ```Tables in non-LaTeX output formats will always be placed after the code block. For LaTeX/PDF output formats, tables have the same issue as figures: they may float. If you want to avoid this behavior, you will need to use the LaTeX package longtable, which can break tables across multiple pages. This can be achieved by adding \usepackage{longtable} to your LaTeX preamble, and passing longtable = TRUE to kable().
If you are looking for more advanced control of the styling of tables, you are recommended to use the kableExtra package, which provides functions to customize the appearance of PDF and HTML tables. Formatting tables can be a very complicated task, especially when certain cells span more than one column or row. It is even more complicated when you have to consider different output formats. For example, it is difficult to make a complex table work for both PDF and HTML output. We know it is disappointing, but sometimes you may have to consider alternative ways of presenting data, such as using graphics.
We explain in Section 12.3 how the bookdown package extends the functionality of rmarkdown to allow for figures and tables to be easily cross-referenced within your text.
References
Xie, Yihui. 2015. Dynamic Documents with R and Knitr. 2nd ed. Boca Raton, Florida: Chapman; Hall/CRC. https://yihui.name/knitr/.You may also consider the pander package. There are several other packages for producing tables, including xtable, Hmisc, and stargazer, but these are generally less compatible with multiple output formats.↩︎
Tag » Code Snippets R Markdown
-
Code Chunks - R Markdown - RStudio
-
7.3 Style Code Blocks And Text Output | R Markdown Cookbook
-
Format Code As A Code Block In R Markdown - Stack Overflow
-
R Markdown Code Snippets In RStudio - YouTube
-
Extended Syntax - Markdown Guide
-
RStudio Snippets For Markdown | Thought Splinters
-
27 R Markdown | R For Data Science
-
RStudio Snippets
-
R Markdown Document
-
How To Use R Markdown (part One) - R-bloggers
-
Document Code With R Markdown | NSF NEON
-
My Snippets For RStudio (or Elsewhere) - GitHub
-
R Markdown Notebook In VS Code - Towards Dev
-
Tips And Tricks In RStudio And R Markdown - Stats And R