This is a tutorial for R markdown. It also serves as a sample R markdown code. Please check the source code of this document.

What is R markdown?

Creating an R markdown document

In RStudio, click File -> New File -> R Markdown….

RStudio will create a skeleton file with some basic explanations. Read those.

You can compile the source code into HTML or PDF. I recommend HTML because it can adjust fontsize, linebreak, etc. according to the device.

R markdown cheatsheet

LaTeX

If you know LaTeX, a popular language for writing academic documents, you can use it in R markdown.

R markdown understands LaTeX syntax — just write them.

For the class, we use it to write math symbols and equations, which we discuss below.

Writing math symbols and equations

Please check the source code of this document to see how to write math equations.

Examples - read the source code!

Pythagorean theorem.

\[ a^2 + b^2 = c^2 \]

Arithmetic mean \(\geq\) Geometric mean \(\geq\) Harmonic mean.

\[ \frac{1}{n}\sum_{i=1}^N X_i \geq \left( \prod_{i=1}^N X_i \right)^{1/N} \geq \frac{1}{\sum_{i=1}^N 1/X_i}. \]

Greek letters, plain texts and multiple lines.

\[ \begin{aligned} line 1 &= \alpha + \beta \\ \text{plain text} &= \gamma + \delta \\ line 3 &= \lambda + \sigma \\ \textbf{bold plain text} &= \Lambda + \Sigma \end{aligned} \]

Caligraphic, blackboard bold and bold. \[ \mathcal{F}, \mathbb{F}, \mathbf{F}. \]

If you need a math symbol but you don’t know what to type, go to http://detexify.kirelabs.org/classify.html and draw the symbol using your mouse! For example, you can draw \(\pm\) there and see that the command is “pm”.

Embedding R

Below is an example of the R code (which we shall call “chunk”) run within the document.

Sys.setenv(lang="EN") ### this command sets the R locale to English ###
courseNo = "ECON 21130"
print(courseNo)
## [1] "ECON 21130"

Below is an example.

courseTitle = "Topics in Microeconometrics"
print(paste(courseNo, courseTitle, sep = " - "))
## [1] "ECON 21130 - Topics in Microeconometrics"

Below is an example.

ROOT2 = 1.414

In the above chunk, I specified eval=FALSE option. So the above chunk is not executed, which means ROOT2 is not defined.

In the below chunk, we can confirm that ROOT2 is not defined.

print(ROOT2)
## Error in print(ROOT2): object 'ROOT2' not found

If you check the source code of this document, you will notice that I specified error=TRUE in the above chunk.

You must specify this option if you want R to print the error message. Otherwise the source code will not be compiled into the HTML document due to the error.