Abstract

The SciViews web site is completely refactored.

This page shows how posts are presented with the new skin.


Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents (among other possible formats). For more details on using R Markdown see http://rmarkdown.rstudio.com. This version supports YAML header starting and ending with three dashes (---). It also includes improvements for scientific documents (figures and tables numbering and reference, equations and equations numbering, citations and bibliographic references, …)

Here are the various R Markdown features you can use:

Headers

  • Header with 6 levels, either with #, or with underline:

Header 1

Some text…

Header 2

Some text…

Header 3

Some text…

Header 4

Some text…

Header 5

Some text…

Header 6

Some text…

An alternate syntax for headers:

Header 1

Header 2

Images

  • To insert images in your document, you use:
A nice little cat.

A nice little cat.

The official R logo.

The official R logo.

An inline image: A small SciViews Box logo.. Note here that when an image appears alone in its line, it is interpreted as a figure (possibly with caption), and otherwise, it is interpeted as an inline image.

Hugo shortcodes

  • Tweeter. In R Markdown, you should not use the {{< tweet 936232450006704128 >}} syntax. Instead, you should use:
blogdown::shortcode('tweet', '936232450006704128')
  • Youtube:
  • Vimeo:
  • Github Gist:
  • Instagram:

Figure:

A nice little cat

Tables

There are several ways to present tables.

  • Simple tables are easy to create. Header and rows must be on two lines, and column alignment is determined according to the position of the header relative to the line under it. Tables must be surrounded by empty lines and an optional caption may be added above or below the table, starting with Table: or : (which is stripped off).
Demonstration of a simple table with caption.
Right Left Center Default
12 12 12 12
123 123 123 123
1 1 1 1
  • The header may be omitted, but then, the ending line is mandatory.
A table without header.
12 12 12 12
123 123 123 123
1 1 1 1
  • Multiline tables start and end with a line of dashes. Cells are separated by spaces (in case of a single row table, add the empty line too, otherwise, the table is interpreted as a sinlge-line table). In multiline tables, the writer tries to respect the relative size of the columns that appear in the markdown document.
A multiline table.
Centered Header Default Aligned Right Aligned Left Aligned
First row 12.0 * Example of a row that spans multiple lines.
Second row 5.0 * Here’s another one. Note the blank line between rows.
  • Headers can be omitted too in multiline tables (note that this could be used as a simple formatting hack to place –short– material on several columns!):
Here’s a multiline table without headers.
First row 12.0 Example of a row that spans multiple lines.
Second row 5.0 Here’s another one. Note the blank line between rows.
  • Grid tables (rows with = separate headers and can be omitted for headerless tables). Apparently, more formatting is allowed in gridded tables, like list items:
Sample grid table.
Fruit Price Advantages
Bananas $1.34
  • built-in wrapper
  • bright color
Oranges $2.10
  • cures scurvy
  • tasty
  • Pipe tables look like this (beginning and end pipes are optional, and optional colon indicates alignment, header can be omitted but not the lines, and finally, although ugly, pipe do not need to align). Note that table characters like | cannot appear in the table and this form does not support multiline tables. The semicolumn :may be used to indicate alignment inside each column, but it is an optional feature.
A typical pipe table.
Right Left Default Center
12 12 12 12
123 123 123 123
* 1 1 1 1

Equations

  • Inline equations like \(\frac{1}{n} \sum_{i=1}^{n} x_{i} + \beta\), or \(f(\alpha, \beta) \propto x^{\alpha-1}(1-x)^{\beta-1}\).

  • Display equation

\[ \frac{1}{n} \sum_{i=1}^{n} x_{i} + \beta \]

Here is a more complex example spanning on several lines:

\[ \begin{aligned} \dot{x} & = \sigma(y-x) \\ \dot{y} & = \rho x - y - xz \\ \dot{z} & = -\beta z + xy \end{aligned}\]

If you feel difficult to write LaTeX equations, there are inline LateX equation editors like this one, and you don’t need to install anything on your computer to used them. Also, there is a R Studio addin provided with the bookdown R package to ease entering LaTeX equations in your R Markdown document.

Knitr chunks

The R package knitr is used to insert R code withing your Markdown document, which makes altogether an R Markdown document, usually with the .Rmd extension. Go to knitr homepage for more details.

R chunks

  • A few R commands:
# This is a comment (don't use ##, since it is reserved for output!)
a <- 1 + 1 # Another comment
TRUE; NA; "Some text"
## [1] TRUE
## [1] NA
## [1] "Some text"
summary(cars) # A table
##      speed           dist       
##  Min.   : 4.0   Min.   :  2.00  
##  1st Qu.:12.0   1st Qu.: 26.00  
##  Median :15.0   Median : 36.00  
##  Mean   :15.4   Mean   : 42.98  
##  3rd Qu.:19.0   3rd Qu.: 56.00  
##  Max.   :25.0   Max.   :120.00
  • Normal output versus message versus warning versus error:
# Normal output
cat("Some text...\n")
## Some text...
# A message
message("My very nice message")
## My very nice message
# Output with a warning
1:2 + 1:3
## Warning in 1:2 + 1:3: longer object length is not a multiple of shorter
## object length
## [1] 2 4 4
# An error
non_existing_object
## Error in eval(expr, envir, enclos): object 'non_existing_object' not found
  • R chunk with option to generate a plot5:
An example figure generated by R, from the `cars` dataset.

Figure 1: An example figure generated by R, from the cars dataset.

My plot is here.

  • Another plot:
library(ggplot2)
qplot(speed, dist, data = cars) + geom_smooth(method = "loess")
Distance in function of speed for the `cars` data set.

Figure 2: Distance in function of speed for the cars data set.

I can now reference this figure in the text (see this plot).

  • R chunk with option to generate a table :
Table 1: The first few lines of the iris data set.
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
5.1 3.5 1.4 0.2 setosa
4.9 3.0 1.4 0.2 setosa
4.7 3.2 1.3 0.2 setosa
4.6 3.1 1.5 0.2 setosa
5.0 3.6 1.4 0.2 setosa
5.4 3.9 1.7 0.4 setosa

Now, I can refer to this table (see this Table).

Tables using xtable

The xtable R package offers an alternative to output well-formatted tables in an R Markdown document:

library(xtable)
data(tli)
## Demonstrate data.frame... can also export many objects!
tli.table <- xtable(tli[1:10, ])
digits(tli.table)[c(2, 6)] <- 0
## Choose one of these!
print(tli.table, floating = FALSE, type = "html")
grade sex disadvg ethnicty tlimth
1 6 M YES HISPANIC 43
2 7 M NO BLACK 88
3 5 F YES HISPANIC 34
4 3 M YES HISPANIC 65
5 8 M YES WHITE 75
6 5 M NO BLACK 74
7 8 F YES HISPANIC 72
8 4 M YES BLACK 79
9 6 M NO WHITE 88
10 7 M YES HISPANIC 87

Tables using pander

The pander package can output various objects in pandoc:

library(pander)
# You can change default pander options:
panderOptions('table.alignment.default', function(df)
  ifelse(sapply(df, is.numeric), 'right', 'left'))
panderOptions('table.split.table', Inf)
panderOptions('big.mark', ",")
panderOptions('keep.trailing.zeros', TRUE)
pander(head(iris))
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
5.1 3.5 1.4 0.2 setosa
4.9 3.0 1.4 0.2 setosa
4.7 3.2 1.3 0.2 setosa
4.6 3.1 1.5 0.2 setosa
5.0 3.6 1.4 0.2 setosa
5.4 3.9 1.7 0.4 setosa

There are many other packages to output well-formatted tables from R objects, like: stargazer, table1, tables, flextable, formattable, htmlTable, huxtable, kableExtra, pixiedust, tangram, texreg, ztable, etc.

Inline R expressions and special chunks

  • Inline R expression like 2, or R version 3.4.4 (2018-03-15).

  • Rcpp code chunks can also be included in your document:

#include <Rcpp.h>

// [[Rcpp::export]]
int fibonacci(const int x) {
    if (x == 0 || x == 1) return(x);
    return (fibonacci(x - 1)) + fibonacci(x - 2);
}

Because fibonacci was defined with the Rcpp::export attribute it can now be called as a normal R function:

fibonacci(10L)
## [1] 55
fibonacci(20L)
## [1] 6765
  • An R chunk that is displayed, but not executed:
library(knitr)
knit('R Markdown V2 Syntax.Rmd')
  • A Python chunk:
import sys
print(sys.version)
## 2.7.10 (default, Feb 22 2019, 21:17:52) 
## [GCC 4.2.1 Compatible Apple LLVM 10.0.1 (clang-1001.0.37.14)]

Citations

Thanks to Pandoc, it is rather easy to insert citations in your text. First, you need to specify a bibliography file in a YAML section. A number of formats are supported, but to remain compatible with LaTeX, use BibTeX (.bibtex) or BibLaTeX (.bib) format only. Note that the bibliography folder, like for figures is two folders ahead in the relative path, i.e., ../../bibliography/<my-file.bib>.

The file we use here is named bibliography.bib. It is enough to refer to it in a YAML section. However, we will also add more reference to the bibliography later on. So, we first copy this file into bibliography-full.bib and then, we refer to the later file instead.

  • A references field can also be included in a YAML section for self-contained bibliography (and you can use both at the same time!).
  • The R package knitcitations uses pandoc citations, but enhances its mechanisms by allowing to add citations by DOIs or URL and by linking to cited papers directly. You need to start loading the package and clean up citations.

You can use references citations contained in your bibliography inside square brackets, separated by semicolons and each citation must be composed using @ + citation identifier. For instance (Greenwade 1993; Fenner 2012), or (see Fenner 2012, pp. 12–17; also Greenwade 1993, ch. 2). Use a minus sign before the reference to suppress mention of the author: as Greenwade (1993) indicated, “bla bla”. You can also write the inline citation this way: Fenner (2012, p. 10) says “bla”.

Finally, you can include citations in the references without citing them by using a nocite entry in a YAML block:

---
nocite:
 | @item1, @item2
---

By default, the Chicago author-date format is used by Pandoc, but you can use a different style by specifying a CSL 1.0 style in a csl metadata entry in a YAML block. The RStudio rmarkdown site indicates two interesting pages to get CSL files: CSL official repository and Zotero styles page that allows easy browsing. Here, we use the Marine Biology style.

As already mentioned, an addition to this mechanism is provided by the knitcitations package that allows to build citations from DOIs, or URL into Pandoc-compatible citations. The question of independent .bib file, and/or need for an Internet link to compile the document is discussed here http://blog.martinfenner.org/2013/06/19/citations-in-scholarly-markdown/.

One big lack in this approach is no link between the citation and the reference.

Now for knitcitations citations… We can add a citation by DOI (Abrams et al. 2012), or Boettiger and Hastings (2013). Since a citation like name_year is automatically created, one do not need to recite the same items by DOI, but one can cite like this (Abrams et al. 2012), which should be the same as (Abrams et al. 2012). Finally, one can also cite R bibentry objects directly, like (Xie 2014, 2015, 2019). All these approaches are combinable with traditional pandoc citations, providing these citations are already included in the .bib file.

Finally, don’t forget to generate the complete .bib file by appending the following last R chunk into your document in order to add the knitcitations in your document properly:

write.bibtex(file = "../../bibliography/bibliography-full.bib", append = TRUE)

Note how the references are included automatically at the end of the document. Do not forget to put an adequate header by yourself!

References

Abrams PA, Ruokolainen L, Shuter BJ, McCann KS (2012) Harvesting creates ecological traps: Consequences of invisible mortality risks in predatorprey metacommunities. Ecology 93:281–293. doi: 10.1890/11-0011.1

Boettiger C, Hastings A (2013) No early warning signals for stochastic transitions: Insights from large deviation theory. Proceedings of the Royal Society B: Biological Sciences 280:20131372–20131372. doi: 10.1098/rspb.2013.1372

Fenner M (2012) One-click science marketing. Nature Materials 11:261–263. doi: 10.1038/nmat3283

Greenwade G (1993) The Comprehensive Tex Archive Network (CTAN). TUGBoat 14:342–351

Xie Y (2019) Knitr: A general-purpose package for dynamic report generation in r

Xie Y (2015) Dynamic documents with R and knitr, 2nd edn. Chapman; Hall/CRC, Boca Raton, Florida

Xie Y (2014) Knitr: A comprehensive tool for reproducible research in R. In: Stodden V, Leisch F, Peng RD (eds) Implementing reproducible computational research. Chapman; Hall/CRC


  1. This is my simple footnote.

  2. Footnotes can span on multiple paragraphs, providing you indent them with four spaces:

    • A list item

    Another paragraph belonging to the note.

  3. Inline footnotes are easier to write right in your text, but they can only span on a single paragraph.

  4. Note that you cannot include the number inside the link, unfortunately.

  5. Do not use underscore _ in the label of your chunk to use it as a link!