` in HTML and it gave it an identity or `id`, and for this example here, it gave in HTML code `
`. It is important to notice that the original text of the heading `"The 'R twist' of Markdown: R Markdown"` is transformed into `"the-r-twist-of-markdown-r-markdown"` where all signs have been removed, spaces replaced by a `"-"`, and all characters are in lower case.
#### Linking to anywhere in the document
There is, to my knowledge, no native way of doing this in Markdown. One must borrow some HTML code and it is very simple. You must add an `anchor` link in your document. where you want the page to line up. So in the [link example](#link_ref) example above point to the absolute link example, the code is like that.
```
So in the [link example](#link_ref) example above point to the absolute link example, the code is like that.
```
I thus added in the line just above where I want the link this HTML code where `
` stands for `anchor`.
```
```
### Footnotes
You can add footnotes in the text by adding `[^footnote]` right next to the word concerned and add the `[^footnote]:` with the text next to it JUST BEFORE the `# References` section.
### Images
To add images in a document, add a `!` in front of the same syntax as for links such as:
```
![](https://www.bae.ncsu.edu/wp-content/themes/riddick/dist/images/ncstate-logos/ncstate-brick-2x2-red.png)
```
to render:
![](https://www.bae.ncsu.edu/wp-content/themes/riddick/dist/images/ncstate-logos/ncstate-brick-2x2-red.png)
You can modify the width of the image by adding e.g., `{width = 50%}` to have the image take 50% of the width of the page
```
![](https://www.bae.ncsu.edu/wp-content/themes/riddick/dist/images/ncstate-logos/ncstate-brick-2x2-red.png){width=50%}
```
to render:
![](https://www.bae.ncsu.edu/wp-content/themes/riddick/dist/images/ncstate-logos/ncstate-brick-2x2-red.png){width=50%}
To align the image, there is no native way of doing it in Markdown, so you can use a little bit of HTML code like `
... ` such as below. Apparently, it might not work that great in html5 though...
```
![](https://www.bae.ncsu.edu/wp-content/themes/riddick/dist/images/ncstate-logos/ncstate-brick-2x2-red.png){width=25%}
```
to render:
![](https://www.bae.ncsu.edu/wp-content/themes/riddick/dist/images/ncstate-logos/ncstate-brick-2x2-red.png){width=33%}
You can add a caption by just adding the "Using a caption this time" in the brackets.
![Using a caption this time](https://www.bae.ncsu.edu/wp-content/themes/riddick/dist/images/ncstate-logos/ncstate-brick-2x2-red.png){width=33%}
```
![Using a caption this time ](https://www.bae.ncsu.edu/wp-content/themes/riddick/dist/images/ncstate-logos/ncstate-brick-2x2-red.png){width=33%}
```
Now, you can add an image in the text like this ![Using a caption this time](https://www.bae.ncsu.edu/wp-content/themes/riddick/dist/images/ncstate-logos/ncstate-brick-2x2-red.png){width=33%} and it will work just fine.
```
Now, you can add an image in the text like this ![Using a caption this time](https://www.bae.ncsu.edu/wp-content/themes/riddick/dist/images/ncstate-logos/ncstate-brick-2x2-red.png){width=33%} and it will work just fine.
```
However, you can see that the caption was not added. So for the caption to be added, there needs to be a return before and after the image code. If you include the image like this
![Using a caption this time](https://www.bae.ncsu.edu/wp-content/themes/riddick/dist/images/ncstate-logos/ncstate-brick-2x2-red.png){width=33%}
The caption does not appear.
```
However, you can see that the caption was not added. So for the caption to be added, there needs to be a return before and after the image code. If you include the image like this
![Using a caption this time](https://www.bae.ncsu.edu/wp-content/themes/riddick/dist/images/ncstate-logos/ncstate-brick-2x2-red.png){width=33%}
The caption does not appear.
```
But if you leave a blank line before and after like this
![Using a caption this time](https://www.bae.ncsu.edu/wp-content/themes/riddick/dist/images/ncstate-logos/ncstate-brick-2x2-red.png){width=33%}
The caption will appear.
```
But if you leave a blank line before and after like this
![Using a caption this time](https://www.bae.ncsu.edu/wp-content/themes/riddick/dist/images/ncstate-logos/ncstate-brick-2x2-red.png){width=33%}
The caption will appear.
```
Now if you want to center **both figure and caption**, you need to add `
` a blank line, the image code, a blank line, then ``, and it will appear like this:
![*__Using a caption this time__*](https://www.bae.ncsu.edu/wp-content/themes/riddick/dist/images/ncstate-logos/ncstate-brick-2x2-red.png){width=33%}
```
![*__Using a caption this time__*](https://www.bae.ncsu.edu/wp-content/themes/riddick/dist/images/ncstate-logos/ncstate-brick-2x2-red.png){width=33%}
```
And you can see that adding `*__ __*` aound the caption text put the caption in bold and italic as well.
To have an image linked to a particular website, you can use this code:
```
[![caption](https://www.bae.ncsu.edu/wp-content/themes/riddick/dist/images/ncstate-logos/ncstate-brick-2x2-red.png)](https://www.bae.ncsu.edu/wp-content/themes/riddick/dist/images/ncstate-logos/ncstate-brick-2x2-red.png)
```
If you do that, however, the caption will not show any more, even though you have the proper number of lines before and after. If you want a caption below with a link, you will have to add this underneath. So if you want both the image and the caption to have clickable links, and centered like this
[![](https://www.bae.ncsu.edu/wp-content/themes/riddick/dist/images/ncstate-logos/ncstate-brick-2x2-red.png){width=33%}](https://www.bae.ncsu.edu/wp-content/themes/riddick/dist/images/ncstate-logos/ncstate-brick-2x2-red.png)
[This is the corresponding clickable caption I want](https://www.bae.ncsu.edu/wp-content/themes/riddick/dist/images/ncstate-logos/ncstate-brick-2x2-red.png)
you would write:
```
[![](https://www.bae.ncsu.edu/wp-content/themes/riddick/dist/images/ncstate-logos/ncstate-brick-2x2-red.png){width=33%}](https://www.bae.ncsu.edu/wp-content/themes/riddick/dist/images/ncstate-logos/ncstate-brick-2x2-red.png)
[This is the corresponding clickable caption I want](https://www.bae.ncsu.edu/wp-content/themes/riddick/dist/images/ncstate-logos/ncstate-brick-2x2-red.png)
```
## Editing equations in R Markdown
We do not write nearly as much math in our field than our colleagues in statistics or math. But we do enough to have a bit of a tutorial. I have borrowed this entire section from the [excellent tutorial from Dr Shalizi](http://www.stat.cmu.edu/~cshalizi/rmarkdown/#math-in-r-markdown) again. R Markdown gives you the syntax to render complex mathematical formulas and derivations, and have them displayed very nicely. Like code, the math can either be inline or set off (displays).
### Inline equations
Inline math is marked off witha pair of dollar
signs (`$`), as $\pi r^2$ or $e^{i\pi}$.
```
Inline math is marked off witha pair of dollar
signs (`$`), as $\pi r^2$ or $e^{i\pi}$.
```
### Set off equations
Mathematical displays are marked off with `\[` and `\]`, as in
\[
e^{i \pi} = -1
\]
```
Mathematical displays are marked off with `\[` and `\]`, as in
\[
e^{i \pi} = -1
\]
```
Once your text has entered math mode, R Markdown turns over the job of
converting your text into math to a different program, called LaTeX.
This is the most common system for typesetting mathematical documents
throughout the sciences, and has been for decades. It is extremely powerful,
stable, available on basically every computer, and completely free. It is
also, in its full power, pretty complicated. Fortunately, the most useful
bits, for our purposes, are actually rather straightforward.
### Elements of Math Mode
* Most letters will be rendered in italics (compare: a vs. `a` vs. $a$; only
the last is in math mode, i.e., `$a$`). The spacing between letters also follows the conventions for math, so don't treat it as just another way of getting italics. (Compare _speed_, in simple italics, with $speed$, in math mode, i.e., `$speed$`)
* Greek letters can be accessed with the slash in front of their names, as `\alpha` for $\alpha$. Making the first letter upper case gives the upper-case letter, as in `\Gamma` for $\Gamma$ vs. `\gamma` for $\gamma$. (Upper-case alpha and beta are the same as Roman A and B, so no special commands for them.)
* There are other "slashed" (or "escaped") commands for other mathematical symbols:
+ `\times` for $\times$
+ `\cdot` for $\cdot$
+ `\leq` and `\geq` for $\leq$ and $\geq$
+ `\subset` and `\subseteq` for $\subset$ and $\subseteq$
+ `\leftarrow`, `\rightarrow`, `\Leftarrow`, `\Rightarrow`, `\rightleftharpoons` for $\leftarrow$, $\rightarrow$, $\Leftarrow$, $\Rightarrow$, $\rightleftharpoons$
+ `\approx`, `\sim`, `\equiv` for $\approx$, $\sim$, $\equiv$
+ See, e.g., http://web.ift.uib.no/Teori/KURS/WRK/TeX/symALL.html for a fuller
listing of available symbols. (http://tug.ctan.org/info/symbols/comprehensive/symbols-a4.pdf lists _all_ symbols available in `LaTeX`, including many non-mathematical special chracters)
* Subscripts go after an underscore character, `_`, and superscripts go after a caret, `^`, as `\beta_1` for $\beta_1$ or `a^2` for $a^2$.
* Curly braces are used to create groupings that should be kept together, e.g., `a_{ij}` for $a_{ij}$ (vs. `a_ij` for $a_ij$).
* If you need something set in ordinary (Roman) type within math mode, use `\mathrm`, as `t_{\mathrm{in}}^2` for $t_{\mathrm{in}}^2$.
* If you'd like something set in an outline font ("blackboard bold"), use `\mathbb`, as `\mathbb{R}` for $\mathbb{R}$.
* For bold face, use `\mathbf`, as
```
(\mathbf{x}^T\mathbf{x})^{-1}\mathbf{x}^T\mathbf{y}
```
for
\[
(\mathbf{x}^T\mathbf{x})^{-1}\mathbf{x}^T\mathbf{y}
\]
* Accents on characters work rather like changes of font: `\vec{a}` produces
$\vec{a}$, `\hat{a}` produces $\hat{a}$. Some accents, particularly hats,
work better if they space out, as with `\widehat{\mathrm{Var}}` producing
$\widehat{\mathrm{Var}}$.
* Function names are typically written in romans, and spaced differently: thus
$\log{x}$, not $log x$. `LaTeX`, and therefore `R Markdown`, knows about a
lot of such functions, and their names all begin with `\`. For instance:
`\log`, `\sin`, `\cos`, `\exp`, `\min`, etc. Follow these function names
with the argument in curly braces; this helps `LaTeX` figure out what exactly
the argument is, and keep it grouped together with the function name when
it's laying out the text. Thus `\log{(x+1)}` is better than `\log (x+1)`.
* Fractions can be created with `\frac`, like so:
```
\frac{a+b}{b} = 1 + \frac{a}{b}
```
produces
\[
\frac{a+b}{b} = 1 + \frac{a}{b}
\]
* Sums can be written like so:
```
\sum_{i=1}^{n}{x_i^2}
```
will produce
\[
\sum_{i=1}^{n}{x_i^2}
\]
The lower and upper limits of summation after the `\sum` are both optional.
Products and integrals work similarly, only with `\prod` and `\int`:
\[
n! = \prod_{i=1}^{n}{i}
\]
\[
\log{b} - \log{a} = \int_{x=a}^{x=b}{\frac{1}{x} dx}
\]
`\sum`, `\prod` and `\int` all automatically adjust to the size of the expression being summed, producted or integrated.
* "Delimiters", like parentheses or braces, can automatically re-size to match what they're surrounding. To do this, you need to use `\left` and `\right`,
as
```
\left( \sum_{i=1}^{n}{i} \right)^2 = \left( \frac{n(n-1)}{2}\right)^2 = \frac{n^2(n-1)^2}{4}
```
renders as
\[
\left( \sum_{i=1}^{n}{i} \right)^2 = \left( \frac{n(n-1)}{2}\right)^2 = \frac{n^2(n-1)^2}{4}
\]
+ To use curly braces as delimiters, precede them with slashes, as `\{` and `\}` for $\{$ and $\}$.
* Multiple equations, with their equals signs lined up, can be created
using `eqnarray`, as follows.
```
\[
\begin{eqnarray}
X & \sim & \mathrm{N}(0,1)\\
Y & \sim & \chi^2_{n-p}\\
R & \equiv & X/Y \sim t_{n-p}
\end{eqnarray}
\]
```
\[
\begin{eqnarray}
X & \sim & \mathrm{N}(0,1)\\
Y & \sim & \chi^2_{n-p}\\
R & \equiv & X/Y \sim t_{n-p}
\end{eqnarray}
\]
Notice that `&` surrounds what goes in the middle on each line, and each line (except the last) is terminated with `\\`.
## Code in "Chunks" and within the text
The real beauty of R Markdown is the ability of adding R codes that can be rendered or interpreted along with the mark-up text. R code can be inserted as "chunks" and "in-line".
### Inline code
```
You can embed some r code within the text by using `r '\x60r signif(max(Q),3)\x60'` to give 5 significant digits to the number $\pi$
```
You can embed some r code within the text by using Maximum flow = `r signif(max(Q),3)` m³ to give 5 significant digits to the number $\pi$.
### Code chunks
A code **chunk** is simply an off-set piece of code by itself. It is preceded by ` ```{r} ` on a line by itself, and ended by a line which just says ` ``` `. The code itself goes in between.
The code
```{r cars}
summary(cars)
```
generates these results:
```{r cars}
summary(cars)
```
First, in the syntax, the word "cars" after the "{r " is the name of the chunk (see below). To let the renderer program know that this is now a `R` code, the letter "r" needs to follow the "{".
You can also embed plots, for example:
```{r pressure, echo=FALSE}
plot(pressure)
```
#### Markdown tables and the "kable" function
coming soon...
#### Chunk results options
Code chunks (but not inline code) can take a lot of **options** which modify
how they are run, and how they appear in the document. These options go after
the initial `r` and before the closing `}` that announces the start of a code
chunk. One of the most common options turns off printing out the code,
but leaves the results alone:
` ```{r, echo=FALSE} `
Another runs the code, but includes neither the text of the code nor its output.
` ```{r, include=FALSE} `
This might seem pointless, but it can be useful for code chunks which do set-up
like loading data files, or initial model estimates, etc.
Another option prints the code in the document, but does not run it:
` ```{r, eval=FALSE} `
This is useful if you want to talk about the (nicely formatted) code.
Another option on the results of the code is that it generate all results "as-is", which is very nice when your code generates mark-up text to be rendered by `Pandoc`.
` ```{r, results="asis"} `
By default, the results of a chunk with have `##` as a prefix. You can remove this by putting
` ```{r, comment=FALSE} `
Sometimes, running of the code will generate warnings and messages. These can be turned off in the output by using
` ```{r, warning=FALSE, message = FALSE} `
#### Naming Chunks
You can give chunks names immediately after their opening, like
` ```{r, clevername} `. This name is then used for the images (or other files)
that are generated when the document is rendered.
#### Adjusting figure sizes and alignments
These details are discussed in the accompanying written article on instantaneous vs. interval-average flow data.
#### "Caching" Code Chunks (Re-Running Only When Changed)
By default, R Markdown will re-run all of your code every time you render your
document. If some of your code is slow, this can add up to a lot of time. You
can, however, ask R Markdown to keep track of whether a chunk of code has
changed, and only re-run it if it has. This is called **caching** the chunk.
```{r, cache=TRUE}
summary(cars)
```
```{r, cache=TRUE}
summary(cars)
```
One issue is that a chunk of code which hasn't changed itself might call on
results of earlier, modified chunks, and then we _would_ want to re-run the
downstream chunks. There are options for manually telling R Markdown "this
chunk depends on this earlier chunk", but it's generally easier to
let it take care of that, by setting the `autodep=TRUE` option.
1. If you load a package with the `library()` command, R
Markdown isn't smart enough to check whether the package has changed
(or indeed been installed, if you were missing it). So that won't
trigger an automatic re-running of a cached code chunk.
2. To manually force re-running all code chunks, the easiest thing to do is
to delete the directory R Markdown will create (named something like
_filename_`_cache`) which it uses to store the state of all code chunks.
#### Setting Defaults for All Chunks
You can tell R to set some defaults to apply to all chunks where you don't
specifically over-ride them. Here are the ones I generally use:
```{r, eval=FALSE}
# Need the knitr package to set chunk options
library(knitr)
# Set knitr options for knitting code into the report:
# - Don't print out code (echo)
# - Save results so that code blocks aren't re-run unless code changes (cache),
# _or_ a relevant earlier code block changed (autodep), but don't re-run if the
# only thing that changed was the comments (cache.comments)
# - show the error messages (message)
# - Don't clutter R output with warnings (warning)
# This _will_ leave error messages showing up in the knitted report
opts_chunk$set(echo=FALSE,
cache=TRUE, autodep=TRUE, cache.comments=FALSE,
message=TRUE, warning=FALSE)
```
This sets some additional options beyond the ones I've discussed, like not
re-running a chunk if only the comments have changed (`cache.comments =
FALSE`), and leaving out messages and warnings. (I'd only recommend
suppressing warnings once you're sure your code is in good shape.) I would
typically give this set-up chunk itself the option `include=FALSE`.
You can over-ride these defaults by setting options for individual chunks.
#### More Chunk options
See [http://yihui.name/knitr/options/] for a complete listing of possible chunk options.
# Additional Subtleties
## Creating anchors and links within a page
Now, further down in the document, you might be interested in linking back up if you want to make a link to a particular heading or a particular place in the document that is not a heading.
## Challenges with the "back-ticks"
As I was writing this document, I wanted some of the code to appear as I wrote it, in the "code frames". It turns out that to illustrate that to run a code in line the text, one needs to use `` `r '\x60r signif(pi,5)\x60'` `` , well it is not simple because the `` `r '\x60'` `` is interpreted as containing some code! Therefore, it is not interpreted as text not intended to be rendered...!! So it is a bit of a tour de force to make it appear and being uninterpreted. It turns that in R, if you type
```
'\x60'
```
it will return the "back-tick" symbol `` `r '\x60'` ``. But to display it I have to type in the text
```
== =r '\x60'= ==
```
where for illustration purposes, I have replaced the "back-ticks", by the "=" signs. For another example to display `` `r '\x60r signif(pi,5)\x60'` `` in the text, I actually coded
```
== =r '\x60r signif(pi,5)\x60'= ==
```
where again I have replaced the "back-ticks" with "=" signs.
[^latex]: In the 1970s, the great computer scientist Donald Knuth wrote a
mark-up language, and a rendering program for that language, called `TeX`
(pronounced "tech"), for writing complex mathematical documents. In the 1980s,
the computer scientist Leslie Lamport extended `TeX` in ways that made it
rather more user-friendly, and called the result `LaTeX` (pronounced
"la-tech")
# References