0% found this document useful (0 votes)
46 views9 pages

Introduction to R Markdown Basics

R Markdown is used to create reproducible reports with code, text, and metadata. Reports in R Markdown have three main parts: code chunks, text, and a YAML header. Code chunks allow analysis to be embedded within the report and are denoted using ```r before and after the code. Text is added outside of code chunks to describe and explain the analysis. The YAML header contains metadata about the report like the title and author. Customizations can be made to the report layout and appearance through options specified in the YAML header.

Uploaded by

Hanadi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views9 pages

Introduction to R Markdown Basics

R Markdown is used to create reproducible reports with code, text, and metadata. Reports in R Markdown have three main parts: code chunks, text, and a YAML header. Code chunks allow analysis to be embedded within the report and are denoted using ```r before and after the code. Text is added outside of code chunks to describe and explain the analysis. The YAML header contains metadata about the report like the title and author. Customizations can be made to the report layout and appearance through options specified in the YAML header.

Uploaded by

Hanadi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Introduction to R Markdown

Hanadi Jusufovic

Datacamp Course 2

1 Getting started with R Markdown


R Markdown is used for creating reports. Each report has three parts to it.
• Code
• Text
• Metadata
R Markdown is useful because we can always reproduce the work, and quickly
edit and change the reports.

To add code chunk to the R Markdown we use “‘ r SOME CODE “‘ syntax.

We often want to add text to our report to explain the data. One useful way is
to include headers. We add headers by using hash sign.
# Header1
## Header2
### Header3

The more hashes we use, the smaller the header will be.

To add text we simply type the text. However, we must put text outside of
the code chunk. We should add text after the headers, but before the code
chunk. So when we knit the report the reader will see the headers, dataset
description, and code, in a right order.

If we want to include text in the code we use # in the code section.

If we want to refer to some code in the text, we use back-ticks, ``


To include links in the report, we can use [Name](link). The [Name] will appear
in the text as blue letters that can be clicked on to take us to the link.
Images are added similarly, except we place ! before the square bracket, like
this ![](link to the image)

1
The YAML header is the header at the beginning of Markdown report. It
contains the metadata of the report. It start and ends with - - -
---
title: ”Investment Report”
Author: ”Hanadi”
output: html document
---

We should be careful to specify that the title and author are strings by us-
ing ””, and we can modify the output, for example we can use pdf document.
To generate the date automaticaly, we can use ”`r [Link]()`” command.
We can also format the date, for example: ”‘r format([Link](), %d %B %Y’)‘”
would yield Decimal date, with Month followed by Year.

2 Adding Analyses and Visualizations


To analyze the data, we need to include some packages. We include packages in
the first code chunk. We will include the following packages:
library(readr)
library(dplyr)

We can filter for specific data using filter() function.


For example if we have dataframe called investment services projects, we can
filter for projects in Indonesia for example like so:
indonesia investment projects ←− investment services projects %>%
filter(country == ”Indonesia”)

We can include multiple conditions in the filter, listing them seperated by a


coma.
For example: filter(country == ”Brazil”,
date disclosed >= ”2017-07-01”,
date disclosed <= ”2018-06-30”)

It is useful to name the code chunks for better readability and easier bug fixes.
To do so we include the name is the curly braces after ```
For example: ```{r indonesia-investment-projects}
CODE
```

We can use pipe to sumarize, for example total investments:


brazil investment projects 2018 total ←− brazil investment projects 2018 %>%
summarize(sum total investment = sum(total investment, [Link] = TRUE))

2
To create plots, we simply use package library(ggplot2), and include it in the
code chunk. The file will render when we knit the document. The same way we
plotted in Workshop 2.

We can specify the width and height of the figure by using [Link] and
[Link]. We put this into the curly braces of the code chunk. For exam-
ple:
```{r investment-annual summary, [Link] = 5, [Link] = 3 }
CODE to plot the figure
```
The values specified are in inches.

We can modify the dimension of the figure using [Link] and [Link].
They are the dimensions of the figure in the knit document. They are specified
in the same way as [Link] and [Link], but we use percentages instead.
```{r investment-annual summary, [Link] = ’50%’, [Link] = ’30%’ }
CODE to plot the figure
```

We can modify the alignment of the figure using [Link], and the options are
’left’, ’right’, and ’center’.

To specify these values globally, to apply to each figure in the document, at


the beginning of the document, in a code chunk we can specify them like so:
```{r setup, include = FALSE}
knitr::opts chunk$set([Link] = ’center’, echo = TRUE) ```

To add captions we use [Link] = ’Caption...’ in the curly braces of the code
chunk.

3 Organizing the Report


To better organize the report, we can use lists and tables.
To add bulleted list we use ’-’
For example:

- Region
- East Asia
- Europe
Indenting will result in a sub bullet point.
To create numbered list we use numbers for each point:

3
Region
1. East Asia
2. Europe
To add tables we use kable() function in the code chunk. For example:
```{r tables}
kable(indonesia investment projects 2012 summary)
```

There are many ways to customize the table, but we cannot format the data
within the table to combine the data within the table.

To modify the names of the columns we can do that like so:


```{r tables}
kable(indonesia investment projects 2012 summary,
[Link] = c(”Project Name”, ”Status”, ”Total Investments” ))
```

To modify the alignment, we use align. We specify the alignment of all the
columns in one argument, using letters, c for center, l for left and r for right.
```{r tables}
kable(indonesia investment projects 2012 summary,
[Link] = c(”Project Name”, ”Status”, ”Total Investments”),
align = ”ccc”)
```

Similarly, we can add the caption passing caption argument as a string.

There are code chunks that can be used to modify the report. So far we mention
the data chunk, in which we include the packages, and in this chunk we read
the data, using for example read csv() method ```{r data, include = FALSE}
library(readr)
library(dplyr)
library(ggplot2)
library(knitr)

investment annual salary ←− read csv(path to the file)


```

We can see that we have an option include = FALSE.


Include option determines whether the code and the results appears in the re-
port. When include is FALSE, the code and the results do not appear in the
report.
The other option is echo. When echo is set is FALSE, it prevents the code from
appearing in the report, but displays the results of the code.

4
We often use echo for plots. We want report to include the plot, but we do not
want to include the code that creates the plot.
Lastly, the eval option specifies whether we want to evaluate the code in the
code chunk. If we want to exclude the code chunk from the report, we can set
eval = FALSE. When eval is set to false, the code will not run, and the results
will not be displayed in the report, but the code will still appear in the report.

The Report often includes warnings, that are showed in the knitted document.
The default option for warnings is TRUE. To exclude warnings, we set the warn-
ing chunk option to FALSE.
Since we specified the option include = FALSE, the messages are not includes in
the report. However, if we do not specify the include option, then the messages
will appear. Sometimes, we want to have include = TRUE, but do not want to
show messages. To to this, we set message = FALSE.
Remember that include option specifies whether the code and the results of the
code will appear in the report.
Error option is used to specify how errors will be handled. The default option
for error is FALSE, and if during the knitting, the file has an error, the knitting
will stop when the error is encountered.
If we set error = TRUE, the knit will complete regardless, and the error will be
included in the report.

4 Customizing the Report


To add a table of contents in the YAML header we add toc: true

- - -
title: "Investment Report"
Author: "Hanadi"
output:
html_document
toc: true
date: "‘r format([Link](), ’%d, %B, %Y’)‘"
- - -
We have to use proper intendation, else the file will not knit.
We specify which headers will be included in the table of contents by using
toc depth

- - -
title: "Investment Report"
Author: "Hanadi"

5
output:
html_document
toc: true
toc_depth: 2
date: "‘r format([Link](), ’%d, %B, %Y’)‘"
- - -
The number that we list specifies the size of headers size that will be included
in the table of contents. For example, number 2 means that headers that are
specified with ##, and larger headers specified with # will be included.

We can also add the numbered section by using number sections = true.
- - -
title: "Investment Report"
Author: "Hanadi"
output:
html_document
toc: true
toc_depth: 2
number_sections: true
date: "‘r format([Link](), ’%d, %B, %Y’)‘"
- - -
If we also specify toc float: true the table of contents will appear on the left size
of the report, and it will stay there while we scroll the report.

Furthermore, we can also specify option collapsed under toc float. However,
we have to indent it under toc float. Since we are nesting it under the toc float,
we do not have to specify toc float as true
- - -
title: "Investment Report"
Author: "Hanadi"
output:
html_document
toc: true
toc_float:
collapsed: false
toc_depth: 2
number_sections: true
date: "‘r format([Link](), ’%d, %B, %Y’)‘"
- - -
When collapsed is set to false, the whole content of table remains visible.
Finally, we can specify smooth scroll, also under the toc float. When smooth scroll
is set to false, the reader can click on an element in the table of contents and
jump to it in the file.

6
We can pass parameters to the YAML header. These parameters function sim-
ilarly to function arguments in clasical programming languages.

- - -
title: "Investment Report"
Author: "Hanadi"
output:
html_document
toc: true
toc_float:
collapsed: false
toc_depth: 2
number_sections: true
date: "‘r format([Link](), ’%d, %B, %Y’)‘"
params:
country: Indonesia
- - -
In the code, we want to make sure our code chunks accept this parameter. For
example:
‘‘‘{r country-investment-projects}
country_investment_project <- investment_services_projects %>%
filter(country == params$country)
‘‘‘
Anywhere in the headers, or in the text, or even YAML header, where we are
referencing a specific country, we can replace it by `r params$country `

Similarly, we can add multiple parameters.


- - -
title: "Investment Report"
Author: "Hanadi"
output:
html_document
toc: true
toc_float:
collapsed: false
toc_depth: 2
number_sections: true
date: "‘r format([Link](), ’%d, %B, %Y’)‘"
params:
country: Indonesia
year_start: 2011-07-01

7
year_end: 2012-06-30
- - -
‘‘‘{r country-investment-projects}
country_investment_project <- investment_services_projects %>%
filter(country == params$country,
date_disclosed >= params$year_start,
date_disclosed <= params$year_end)
‘‘‘
We can modify the style of the report. Outside of any code chunk we can put:
<style>
body {
color: red;
}
</style>
Color specifies the color of the report. We can also specify colors using hex
codes, and specify the font
<style>
body {
color: #708090;
font-family: Calibri;
background-color: #F5F5F5
}
</style>
If we include code chunks in our report, we can modify them with pre in style,
table of contents is modifies using #TOC, header using header
<style>
#header {
color: #80000;
background-color: #F5F5F5;
opacity: 0.6;
font-family: Calibri;
font-size: 20px;
}
#TOC {
color: #708090;
font-family: Calibri;
font-size: 16px;
border-color: #708090;
}
body {
color: #708090;
font-family: Calibri;

8
background-color: #F5F5F5
}
pre {
color:#708090;
background-color: #F8F8FF;
}
</style>
Similarly, we can modify title, author, date, by using [Link], [Link], [Link],
respectively.

Instead of putting style in the report, we can put it into a seperate, [Link]
document, and reference it in the YAML header.
- - -
title: "Investment Report"
Author: "Hanadi"
output:
html_document
css: [Link]
toc: true
toc_float:
collapsed: false
toc_depth: 2
number_sections: true
date: "‘r format([Link](), ’%d, %B, %Y’)‘"
params:
country: Indonesia
year_start: 2011-07-01
year_end: 2012-06-30
- - -

You might also like