R Markdown Inline



Markdown supports adding inline code like this, obtained by wrapping text in backticks: `code here` Alternatively, you can put your inline code between and HTML tags. Consider the following markdown code: `This` is an inline code block! This is one too! That would produce the following output: This is an inline code. Keyboard Shortcuts. Knowing R Markdown keyboard shortcuts will save lots of time when creating. This tells R to use bookdown rather than the conventional R Markdown. Notice below you use htmldocument2 to create html output with inline citations. To achieve different styling and formats, you can replace htmldocument2 with other outputs including: tuftehtml2, pdfdocument2, worddocument2, tuftehandout2, and tuftebook2.

  1. R Markdown Inline Variable
  2. R Markdown Inline Latex
  3. R Markdown Inline Code
  4. R Markdown Examples
  • 10 Lesson 5: Code Chunks and Inline Code. Up to this point in the workshop we have mostly just written a standard markdown document. However, we want to integrate R code into our document to create reproducible objects, such as figures, tables, and text.
  • When you render, R Markdown 1. Runs the R code, embeds results and text into.md file with knitr 2. Then converts the.md file into the finished format with pandoc.

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.,

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.,

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. Download therapy i&c usb devices driver. 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 Tuact driver download for windows 10. , 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.,

Besides code chunks, you can also insert values of R objects inline in text. For example:

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:

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%.

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 ![alt text or image title](path/to/image) (e.g., you can specify the image width via out.width). Figure 2.6 provides an example of this.

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.,

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.

Here is a brief introduction to using R Markdown.Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents and much, much more.R Markdown provides the flexibility of Markdown with the implementation of R input and output. For more details on using R Markdown see http://rmarkdown.rstudio.com.

1.1 Basic markdown syntax

1.1.1 Whitespace

Be careful with your spacing.While whitespace largely is ignored, it does at times give markdown signals as to how to proceed.As a habit, try to keep everything left aligned whenever possible, especially as you type a new paragraph.In other words, there is no need to indent basic text in the Rmd document (in fact, it might cause your text to do funny things if you do).

1.1.2 Italics and bold

  • Italics are done like *this* or _this_
  • Bold is done like **this** or __this__
  • Bold and italics is done like ***this***, ___this___, or (the most transparent solution, in my opinion) **_this_**

1.1.3 Inline code

  • Inline code is created with backticks like `this`

1.1.4 Sub and superscript

Sub2 and super2 script is created like this~2~ and this^2^

1.1.5 Strikethrough

  • Strikethrough is done ~~like this~~

1.1.6 ‘Escaping’ (aka “What if I need an actual asterisk?”)

  • To include an actual *, _ or , add another in front of them: *, _,

1.1.7 Endash (–), emdash (—)

  • – and — with -- and ---

1.1.8 Blockquotes

Do like this:

Put a > in front of the line.

1.1.9 Headings

Section headers are created with #’s of increasing number, i.e.

  • # First-level heading
  • ## Second-level heading
  • ### Etc.

In PDF output, a level-five heading will turn into a paragraph heading, i.e. paragraph{My level-five heading}, which appears as bold text on the same line as the subsequent paragraph.

1.1.10 Lists

Unordered list by starting a line with an * or a -:

  • Item 1
  • Item 2

Ordered lists by starting a line with a number.Notice that you can mislabel the numbers and Markdown will still make the order right in the output:

  1. Item 1
  2. Item 2

To create a sublist, indent the values a bit (at least four spaces or a tab):

  1. Item 1
  2. Item 2
  3. Item 3
    • Item 3a
    • Item 3b

1.1.11 Line breaks

The official Markdown way to create line breaks is by ending a line with more than two spaces.

R markdown inline variable

Roses are red.Violets are blue.

This appears on the same line in the output, because we didn’t add spaces after red.

Roses are red.
Violets are blue.

This appears with a line break because I added spaces after red.

I find this is confusing, so I recommend the alternative way: Ending a line with a backslash will also create a linebreak:

Roses are red.
Violets are blue.

To create a new paragraph, you put a blank line.

Therefore, this line starts its own paragraph.

1.1.12 Hyperlinks

  • This is a hyperlink created by writing the text you want turned into a clickable link in [square brackets followed by a](https://hyperlink-in-parentheses)

1.1.13 Footnotes

  • Are createdmy footnote text'>1 by writing either ^[my footnote text] for supplying the footnote content inline, or something like [^a-random-footnote-label] and supplying the text elsewhere in the format shown below:This is a random test.'>2

[^a-random-footnote-label]: This is a random test.

1.1.15 Math

The syntax for writing math is stolen from LaTeX. To write a math expression that will be shown inline, enclose it in dollar signs.- This: $A = pi*r^{2}$ Becomes: (A = pi*r^{2})

To write a math expression that will be shown in a block, enclose it in two dollar signs.
This: $$A = pi*r^{2}$$

Becomes:[A = pi*r^{2}]

To create numbered equations, put them in an ‘equation’ environment and give them a label with the syntax (#eq:label), like this:

Becomes:[begin{equation}fleft(kright)=binom{n}{k}p^kleft(1-pright)^{n-k}tag{1.1}end{equation}]

For more (e.g. how to theorems), see e.g. the documentation on bookdown.org

1.2 Executable code chunks

The magic of R Markdown is that we can add executable code within our document to make it dynamic.

R Markdown Inline Variable

We do this either as code chunks (generally used for loading libraries and data, performing calculations, and adding images, plots, and tables), or inline code (generally used for dynamically reporting results within our text).

R markdown inline variable

The syntax of a code chunk is shown in Figure 1.1.

Common chunk options include (see e.g. bookdown.org):

  • echo: whether or not to display code in knitted output
  • eval: whether or to to run the code in the chunk when knitting
  • include: whether to include anything from the from a code chunk in the output document
  • fig.cap: figure caption
  • fig.scap: short figure caption, which will be used in the ‘List of Figures’ in the PDF front matter

IMPORTANT: Do not use underscoores in your chunk labels - if you do, you are likely to get an error in PDF output saying something like “! Package caption Error: caption outside float.”

1.2.1 Setup chunks - setup, images, plots

An R Markdown document usually begins with a chunk that is used to load libraries, and to set default chunk options with knitr::opts_chunk$set.

In your thesis, this will probably happen in index.Rmd and/or as opening chunks in each of your chapters.

1.2.2 Including images

Code chunks are also used for including images, with include_graphics from the knitr package, as in Figure 1.2

Figure 1.2: Oxford logo

Useful chunk options for figures include:

  • out.width (use with a percentage) for setting the image size
  • if you’ve got an image that gets waaay to big in your output, it will be constrained to the page width by setting out.width = '100%'
Inline

Figure rotation

You can use the chunk option out.extra to rotate images.

The syntax is different for LaTeX and HTML, so for ease we might start by assigning the right string to a variable that depends on the format you’re outputting to:

Then you can reference that variable as the value of out.extra to rotate images, as in Figure 1.3.

Figure 1.3: Oxford logo, rotated

1.2.3 Including plots

Similarly, code chunks are used for including dynamically generated plots.You use ordinary code in R or other languages - Figure 1.4 shows a plot of the cars dataset of stopping distances for cars at various speeds (this dataset is built in to R).

Figure 1.4: A ggplot of car stuff

Under the hood, plots are included in your document in the same way as images - when you build the book or knit a chapter, the plot is automatically generated from your code, saved as an image, then included into the output document.

1.2.4 Including tables

Tables are usually included with the kable function from the knitr package.

Table 1.1 shows the first rows of that cars data - read in your own data, then use this approach to automatically generate tables.

Table 1.1: A knitr kable table
speeddist
42
410
74
722
816
910
  • Gotcha: when using kable, captions are set inside the kable function
  • The kable package is often used with the kableExtra package

1.2.5 Control positioning

One thing that may be annoying is the way R Markdown handles “floats” like tables and figures.In your PDF output, LaTeX will try to find the best place to put your object based on the text around it and until you’re really, truly done writing you should just leave it where it lies.

In general, you should allow LaTeX to do this, but if you really really need a figure to be positioned where you put in the document, then you can make LaTeX attempt to do this with the chunk option fig.pos='H', as in Figure 1.5:

Figure 1.5: An Oxford logo that LaTeX will try to place at this position in the text

R Markdown Inline Latex

As anyone who has tried to manually play around with the placement of figures in a Word document knows, this can have lots of side effects with extra spacing on other pages, etc.Therefore, it is not generally a good idea to do this - only do it when you really need to ensure that an image follows directly under text where you refer to it (in this document, I needed to do this for Figure 3.1 in section 3.1.4).For more details, read the relevant section of the [R Markdown Cookbook]https://bookdown.org/yihui/rmarkdown-cookbook/figure-placement.html).

1.3 Executable inline code

‘Inline code’ simply means inclusion of code inside text.The syntax for doing this is `r R_CODE`For example, `r 4 + 4` will output 8 in your text.

R Markdown Inline Code

You will usually use this in parts of your thesis where you report results - read in data or results in a code chunk, store things you want to report in a variable, then insert the value of that variable in your text.For example, we might assign the number of rows in the cars dataset to a variable:

We might then write:
“In the cars dataset, we have `r num_car_observations` observations.”

Which would output:
“In the cars dataset, we have 50 observations.”

1.4 Executable code in other languages than R

R Markdown Examples

If you want to use other languages than R, such as Python, Julia C++, or SQL, see the relevant section of the R Markdown Cookbook