If you are new to R markdown, please watch the video before starting.

1 YAML Header

Guiding to R Markdown Built Process

1.1 Parameters

You may include these parameters in the YAML header:

---
output:
  bookdown::pdf_book:
    toc_depth: 2
    fig_height : 5
    fig_width : 8
    citation_package: natbib
    includes:
      in_header: import.sty 
      before_body: title.sty
documentclass: book     
bibliography: reference.bib
csl: ama.csl
geometry: [top=1.5in, bottom=1.5in, right=1in, left=1in]
linestretch: 1
fontsize: 11pt
---

1.2 Explaination

  • There could be many output formats, for instance html_document/ pdf_document/ word_document/ beamer_presentation etc.
  • citation_package: natbib to work with both author and year
  • in_header: import.sty for loading latex packages
  • before_body: title.sty for creating front pages using latex
  • documentclass could be book, report, letter etc.
  • bibliography: reference.bib for storing referencing information
  • csl: ama.csl for referencing style, for download, click here
  • linestretch and fontsize for formatting text

[NB: Indention in very important in YAML header]

2 Extra Files

2.1 import.sty

For loading Latex Packages

In YAML, we mention : in_header: import.sty

Here, import.sty file will look like this :

% Provides support for setting the spacing between lines 
in a document. 
\usepackage{setspace}

% Longtable allows you to write tables that continue 
to the next page.
\usepackage{longtable}

2.2 title.sty

For setting up Front Pages

In YAML, we mention : before_body: title.sty

Here, title.sty file will look like this :

\pagenumbering{gobble}  % not to use numbering in this title

\begin{center}

\huge{\textbf{Title of the project}}\\

\vspace*{1.5\baselineskip}

\Large{Submitted by\\
Name of the submitter}\\
\Large{Roll of the submitter\\
Affiliation of the submitter}\\

\vspace*{1.5\baselineskip}

\begin{figure}
  \centering
  \includegraphics[width=3cm, height=4.2cm]{logo.JPG}
\end{figure}

\vspace*{1.5\baselineskip}

\Large{Supervised by\\
Name of the supervisor}\\
\Large{Affiliation of the supervisor} \\

\vspace*{1.5\baselineskip}

\Large{This project report submitted in partial fulllment of the requirement for the}\\
\Large{degree of B.S Honors in Applied Statistics.} \\
\vspace*{2.5\baselineskip}
\Large{Institute of Statistical Research and Training(I.S.R.T) \\
University of Dhaka} \\
\Large{Date}\\

\end{center}

The output will look like

Here is some latex command which will help to design title pages

Option Description
newpage Creating a new / page break
vspace Vertical spacing
pagenumbering Numbering page
% Latex comment
\\ Latex line break
includegraphics Adding a picture

For different text size, you can use

\Huge
\huge
\LARGE
\Large
\large
\normalsize (default)
\small
\footnotesize
\scriptsize
\tiny

2.3 Reference.bib

In YAML, we mention : bibliography: reference.bib

Here, reference.bib file will look like this :

@Manual{R-base,
  title = {R: A Language and Environment for Statistical
           Computing},
  author = {{R Core Team}},
  organization = {R Foundation for Statistical Computing},
  address = {Vienna, Austria},
  year = {2019},
  url = {http://www.R-project.org},
}

Here is the procedures for adding citations:

[NB: we have written citation_package: natbib in YAML header]

reference 1 \citep{R-base} 
reference 2 \citet{R-base}

The output will look like this:

here is the procedure for Creating a .bib file

  1. Go to Google Scholar
  2. Open setting (by clicking 3 dots)
  3. Change settings for bibliography manager to show links (save)
  4. Now search for the paper you want to refer
  5. click on improt into Bibtex, copy and past on the created .bib file

3 Code Chunk

3.1 Chunk options

Here is the chunk options :

Option Default Effect
eval True Whether to evaluate the code
echo True Whether to display the code
warning True Whether to display the warnings
error True Whether to display the errors
message True Whether to display the messages

3.2 Global options

  • To set global options that apply to every chunk in your file, call “knitr::opts_chunk$set” in a code chunk.

  • Knitr will treat each option that you pass to knitr::opts_chunk$set as a global default that can be overwritten in individual chunk headers.

  • Example

knitr::opts_chunk$set(message = F, warning = F, 
                      echo = T, fig.height = 3, 
                      fig.width = 5)

4 Document Formatting

4.1 Text

Input :

plain text
*italic*
**bold**
[link](http://bookdown.org/home/)

Output :

plain text
italic
bold
link

4.2 List

Unordered List

Input :

* Unordered list
* item 2
  + sub item 1
  + sub item 2

Output :

  • Unordered list

  • item 2

    • sub item 1
    • sub item 2

Ordered list

Input :

1. Ordered list
2. item 2
  + sub item 1
  + sub item 2  

Output :

  1. Ordered list
  2. item 2
  • sub item 1
  • sub item 2

4.3 Picture

  • Add caption in the third brackets
  • Give the location of your picture on first brackets

Codes :

![R markdown](markdown_logo.png){width=20%}

Result :

R markdown

4.4 Math Expression

Input :

Male and female ratio = $\frac{1}{2}$ (approx)

Theory of special relativity
$$
E = mc^2
$$

Output :

Male and female ratio = \(\frac{1}{2}\) (approx)

Theory of special relativity \[ E = mc^2 \]

Input :

$$
Y = X_1 + X_2
$$

$$
a^2 + b^2 = c^2
$$

Output :

\[ Y = X_1 + X_2 \] \[ a^2 + b^2 = c^2 \]

Input :

$$
Y \sim X\beta_0 + X\beta_1 + \epsilon
$$

$$
\epsilon \sim N(0,\sigma^2)
$$

Output :

\[ Y \sim X\beta_0 + X\beta_1 + \epsilon \] \[ \epsilon \sim N(0,\sigma^2) \]

Input :

$$
\sum_{i = 1}^{n}{(\bar{x} - x_i)^2}
$$

Output :

\[ \sum_{i = 1}^{n}{(\bar{x} - x_i)^2} \] For more expression, click here

5 Beutifying Contents

5.1 Table

  • Make a data frame
  • Put it on kable function for standard outlook
  • load kableExtra package for using kable_styling
library(kableExtra)

head(mtcars) %>%
  kable(digits = 2, booktabs = T, 
        caption = "Motor Trend Car Road Tests Data") %>%
  kable_styling(position = "center", 
                latex_options = "hold_position") %>%
  row_spec(0, bold = T)
Motor Trend Car Road Tests Data
mpg cyl disp hp drat wt qsec vs am gear carb
Mazda RX4 21.0 6 160 110 3.90 2.62 16.46 0 1 4 4
Mazda RX4 Wag 21.0 6 160 110 3.90 2.88 17.02 0 1 4 4
Datsun 710 22.8 4 108 93 3.85 2.32 18.61 1 1 4 1
Hornet 4 Drive 21.4 6 258 110 3.08 3.21 19.44 1 0 3 1
Hornet Sportabout 18.7 8 360 175 3.15 3.44 17.02 0 0 3 2
Valiant 18.1 6 225 105 2.76 3.46 20.22 1 0 3 1

Here,

  • digits for limiting digits after decimal point
  • booktabs for standard outlook
  • hold_position for holding the position for the table
  • row_spec(0, bold=T) for making column names bold
  • for more on table formatting, click here

5.2 Graph

library(ggplot2)
ggplot(data = mtcars) +
  geom_point(aes(x = wt, y = mpg)) +
  scale_x_continuous(breaks = c(2, 3.5, 5), 
                     labels = c("2000lbs", "3500lbs","5000lbs"))+
  labs(title = "Scatter plot between mileage 
       per hour vs weight", 
       subtitle = "From mtcars dataset",
       x = "Weight", y = "Mileage per hour") +
  guides(col=guide_legend(title="Cylinder Number")) +
  theme_bw()

Output :

Here,

  • you can change themes, for instance : theme_classic()/ theme_grey()/ theme_light() etc.
  • scale_x_continuous for changing value labels
  • labs for changing labels of the axis
  • For more, click here

6 Demonstration

  • For practicing, download the folder by clicking here

  • Open .Rproj file

  • Now, Open practice.Rmd

  • Change according to own and knit the file

  • Know, how to work with a project file, watch the video

  • Now, start learning of your own, Best wishes!