R Markdown
R
, RStudio
and
R Markdown
?R
is a popular open-source statistical programming
environment.R
is freely available for download and runs on
Macintosh and Windows computers.RStudio
is another freely available software package
that has numerous features to make data analysis easier.RStudio
is open-source and free program that greatly
facilitates the use of R.RStudio
gives users a text editor where we write
programs, a grapp viewer which displays graphics we make, R console
where we execute our programs, a help section, and many other useful
features.R Markdown
consists of R
and
Markdown
and works on RStudio.
Markdown
is a Markup language proposed by John Gruber
and Aaron Swartz in 2004.R Markdown
enables us to
document R code, statistical results, and comments into one
fileR Markdown
on
RStudio
HTML
, PDF
,
MSWord
, PowerPoint
・HTML
output is highly
recommended
What is
R Markdown
?
・You need to know the difference between plain text
and
rich text
to understand the difference between
Markdown
and R Markdown
plain text
・A document made up of text which does not include
format information
, such as the size and the color of
characters.
・ Rmd
file we use here is also a
plain text.
・Examples of plain text
:
- TextEdit
(macOS
)
- memo
(Windows
)
・ plain text
does not include functions of formatting or
inserting figures and graphs
rich text
・ A document made up of text which includes
format information.
・ Examples of
rich text
:
- Microsoft
Word
- Pages
- LibreOffice Writer
・ rich text
includes functions of formatting or inserting
figures and graphs.
Markup lauguage
?・Markup language
is a language which aims at making a
rich text
only using plain text
・ Examples of Markup language
:
HTML:(HyperText Markup Language)
・html
contains figures, tables, bold characters, and index
in addition to plain text.
・html
is written only by plain text.
・You need a Web Browser
which enables you to visualize the
text.
・ Examples of Web Browser
:
- Firefox
- Chrome
- Edge
・Web Browsers read text
→ Interpret it
→ Visualize it as an output
Markdown
?・Markdown
reconstructs Markup
with simpler
grammar.
R Markdown
?・R Markdown
is a Markdown
which contains R
code and its statistical results altogether.
R Markdown
Procedure | What you do | Steps |
I. Make an
R Project |
:Make a folder (ex: keiryo_2023 ) |
1 - 5 |
II. Make an
Rmd file |
: Make a file (ex: first_trial.Rmd ) |
6 - 10 |
III. Click
Knit |
: Visualize the Rmd file (ex:
first_trial.html ) |
11 - 18 |
R Project
R Project
equals making an
R Project foler
Step_1
:RStusio
→ File
→
New Project
Step_2
:New Directory
in
Create Project
Step_3
:New Project
in Project Type
Step_4
:New Project
, they you will see the
following display below:R Project folder
.R Project folder
on
DesktopBrowse
Step_5
:Browse
, then you will see the following
display below:Desktop
on the left upper side of the
displayopen
Step_6
:Step_6
keiryo_2023
in Directory name:
Create Project
What you should not do in typing at
Directory name
・You should not use Japanese and
space.
・If you want to use symbols, use under bar _
and period
.
・It would be better for you not to use hyphens-
・Start with an alphabet character (Do not start with symbols or
numbers)
Step_7
:R Project
(keiryo_2023
) displayed on the upper rightR Project
Rmd file
Step_8
:File
→ New File
→
R Markdown
Step_9
:How to use R Markdown
in Title:
Author:
"r Sys.Date()"
at Date:
HTML
in Default Output Format:
OK
Step_10
:Rmd file
Rmd file
you just made is
Untitled1
Knit
Step_11
:Knit
Step_12
:Rmd file
you madefirst_trial
in Save As
:Save
What you should not do in typing at
Save As
: ・You should not use Japanese and
space.
・If you want to use symbols, use under bar _
and period
.
・It would be better for you not to use hyphens-
・Start with an alphabet character (Do not start with symbols or
numbers)
注意:
When you visualize the
first_trial.Rmd
、you may see types of displays (either
Step_13
or Step_14
)
Step_13
Step_16
Step_14
Step_15
, and follow the instructionStep_13
:first_trial.html
Step_14
:You see the html display like this outside of the
RStudio
display
This is not convenient, so let the html
file
displayed on the lower right of the monitor within
RStudio
Step_15
Preview in Viewer Pane
Knit
Step_16
:Step_17
: Confiem inside of
R Project folder
Files
on the upper middle of the displayR Project folder
you named
as keiryo_2023
R Project folder
File name | |
.Rhistory |
History file |
first_trial.html |
Displayed on the right side pane
(html file ) |
first_trial.Rmd |
Displayed on the left upper side pane
(Rmd file ) |
keiryo_2023.Rproj |
You click RProject to start this
project |
Step_18
:R Markdown Grammar
R Markdown
Rmd file
is made up of the following 3 parts:Parts | Function |
YAML header |
:Settings |
Chunk | : R code is written within a chunk |
Markdown | : Main body of the document |
R Markdown
Grammaritems |
---|
1. Begin a new line |
2. Emphasis: bold, itlic, underline, color, etc |
3. Bullet points |
4. Headlines |
5. Dividing line |
6. Tables |
7. Pictures |
8. Link |
9. Footnotes |
10. Mathematical formula |
11. Citation |
12. Comments |
13. R code and chunk |
14. Chunk option |
15. Display / Non-display R code and statistical results |
16. Plots |
17. Another way of writing chunk option |
18. Cosmetics on R code |
19. Header options |
20. How to add contents |
21. How to highlight R code |
In Markdown
, hitting return key does not mean
beginning a new line
What you type in Rmd file
right. (Walt Disney) Get a good idea and stay with it. Dog it, and work at it until it’s done
html
outputright. (Walt Disney) Get a good idea and stay with it. Dog it, and work at it until it’s done
Rmd file
# Insert two spaces and hit the return key
Get a good idea and stay with it. # Insert two spaces and hit the return key
Dog it, and work at it until it’s done right. (Walt Disney)
html
output
Get a good idea and stay with it.
Dog it, and work at it until it’s done right. (Walt Disney)
Rmd file
**bold**
You can make it
*italic*
You can make it
<u>underline</u>
You can draw an
~~cancel what you wrote~~
You can
in red]{style="color:red"} or [blue]{style="color:blue"}, for exmple You can [paint letters
html
outputYou can make it bold
You can make a italic
You can draw an underline
You can cancel what you wrote
You can paint letters in red or blue, for example
-
Rmd file
- Questions about Questions
- The Experimental Ideal
- The Selection Problem
- Random Assignment Solves the Selection Problem
- Regression Analysis of Experiments
- THE CORE
- Making Regression Make Sense
- Regression Fundamentals
- Regression and Causality
- Heterogeneity and Nonlinearity
What you see in html
output
Questions about Questions
The Experimental Ideal
THE CORE
Making Regression Make Sense
1.
Rmd file
1. Questions about Questions
2. The Experimental Ideal
2.1 The Selection Problem
2.2 Random Assignment Solves the Selection Problem
2.3 Regression Analysis of Experiments
3. THE CORE
4. Making Regression Make Sense
4.1 Regression Fundamentals
4.2 Regression and Causality
4.3 Heterogeneity and Nonlinearity
html
output#
when you put the title of chapters and
sections#
leads to the biggest characters, ##
leads to the smaller ones, and so onYou can draw a line with ---
What you type in Rmd file
---
html
outputYou an make a table using |
in Markdown
The first row is the header where variable names are
displayed
You make an additional row by adding |---|
You can change the color of background to grey if you use
``
The 1st row is the header and it is shown as bold and centered
automatically
The 1st and 2nd rows to N rows is automatically left
aligned
You can change center aligned
,
right aligned
:
・|:---|
・・・left aligned (default)
・|:---:|
・・・center aliged
・|---:|
・・・right aligned
What you type in Rmd file
|variable names|explanation|
|:---|:---|:---|
| 1. Assign data|`ggplot(data = )`|Choose the data you use|
| 2. Assign variables|`aes()`|Choose the variables you use|
| 3. Assign the type of graphs|`geom_*()`|Choose the graph you use|
html
outputvariable names | explanation | |
---|---|---|
1. Assign data | ggplot(data = ) |
Choose the data you use |
2. Assign variables | aes() |
Choose the variables you use |
3. Assign the type of graphs | geom_*() |
Choose the graph you use |
R Markdown
![](ファイル名)
If the picture you want to insert is not inside the
working directory
(that is, R project folder
,
or keiryo_2023
here)
You need to assign the path to the picture you want to insert -
You made your R project folder
, named
keiryo_2023
→ You don’t have to assign the path
All you have to do is to make a new folder in which you put your picture you want to insert
Let’s take a look at Step_17
R Project folder
Files
in the upper middle side of the
screenR Project folder
, named
keiryo_2023
has in the folderFile names | **** |
.Rhistory |
history file |
first_trial.html |
Output displayed in the right pane
(html file ) |
first_trial.Rmd |
Rmd file displayed in the left upper
pane |
keiryo_2023.Rproj |
You click this icon when you want to open your project |
tsubakuro_2000.JPG
into
keiryo_2023
Confirm that you see tsubakuro_2000.JPG
in
keiryo_2023
Type the following R code OUT OF the
chunk」 and click Knit
What you type in Rmd file
![](tsubakuro_2000.JPG){width=30%} # You can adjust the size
html
output::: {style="text-align: center;"}
![](tsubakuro_2000.JPG){width=30%}
:::
html
outputMake figure folder inside
keiryo_2023
・It would be convenient for you to make
a folder, named, for instance, figure
, within your
R project folder
and put your pictures in it
・This way, you don’t have to assign the path to the picture you want to
insert
・It must be better for you to make figure
folder in
keiryo_2023
and put tsubakuro_2000.JPG
in
it
・If this is the case, then you use the following R code:
::: {style="text-align: center;"}
![](figure/tsubakuro_2000.JPG){width=30%}
:::
tsubakuro_2000.JPG
figure/tsubakuro_2000.JPG
[text](URL)
[]
: text you want to display
()
: URL you want to assign
What you type in Rmd file
's HP](https://www.asanoucla.com/) Click [Asano
html
outputRmd file
The hospital allegory of selection bias would therefore seem to apply to the class size question as well.^foot1]
[
^foot1]: The Angrist-Lavy (1999) results turn up again in chapter 6, as an illustration of the quasi-experimental regression-discontinuity design. [
html
outputHow it works
[^foot1]
・・・Type this at the exact point you want to
insert footnote[^foot1]:
・・・Type what you
want to write in the footnote after the colon
:
^
is called a unique identifier
You can output inline formula using $formula$
or
$$formula$
The usage in mathematical formula is almost the same as
LaTeX
The mathematical formula in R Markdown
is being
rendered by MathJax
MathJax
library is not embeded in
HTML
→ You may not be able to have an appropriate html
output
unless yo are connected to internet
What you type in Rmd file
$Y = a + bx^2$
What you see in html
output
\(Y = a + bx^2\)
If you want to display the formula as an independent row:
What you type in Rmd file
$$Y = a + bx^2$$
What you see in html
output
\[Y = a + bx^2\]
When your mathematical formula is composed of multiple rows, then
you use \begin{aligned}・・・\end{aligned}
as
follow:
What you type in Rmd file
$$
\begin{aligned}-x')^2 + (y - y')^2 < r^2 \\
(x^2 + y^2 < 0.5^2
x
\end{aligned}$$
html
outputIf you want to cite something, then insert >
at
the beginning of the sentence and one space
What you type in Rmd file
"Plotics" as follows:
David Easton defines
> [A] Politics is “the authoritative allocation of values for the society”
html
outputDavid Easton defines “Politics” as follows:
[A] Politics is “the authoritative allocation of values for the society”
R Markdown
R Markdown
lies in the fact that you
can simultaneously display a document
, R code
,
and its statistical results
How to incorporate an R code
into a document
・Type R code
in a
chunk
・A chunk
looks like this:
```{r}
```
・Type R code
into the chunk
→ You can display R code
and its results
library(tidyverse)
read_csv(....)
R code
in a
chunk<- c(1, 2, 3, 4, 5)
x mean(x)
[1] 3
R code
into a
document like this:<- c(1, 2, 3, 4, 5)
x 3 The average value of x is
Incorporate an R code
into a document means that if
you change a value of x
, for example change the value 5 to
10, then the average value of x
should also be updated to a
new mean
To make this happen, you need to incorporate R code
into your document
What you type in Rmd file
html
output<- c(1, 2, 3, 4, 5) x
The average value of x
is 3
<- c(1, 2, 3, 4, 10) x
The average value of x
is 4
R Makrdown
is made up of R
and
Markdown
R
means what lies inside a chunkMarkdown
means what lies out of a chunkR code
and its statistical results by
adding a chunk option{r chunk name, option 1, option 2, ...}
R code
only, or statistical results only<- c(1, 2, 3, 4, 5)
x mean(x)
[1] 3
R code
only, and do not
calculate mean of xType ```{r eval = FALSE}
in chunk option
<- c(1, 2, 3, 4, 5)
x mean(x)
R code
and want to
display its statistical results onlyType ```{r echo = FALSE}
in chunk option
[1] 3
R Markdown
argument | |
fig.height | : height of the figure, inch, default = 7 |
fig.width | : width of the figure, inch default = 7 |
fig.align | : figure position: left ,
center , or right |
fig.cap | : caption |
dpi | : figure resolution, default = 72, more than 300 is preferable if you get it published |
library(tidyverse)
Click hr96-21.csv and download the election data in Japan’s lower house
Make a folder, maned data
in your
R Project folder
Put hr96-21.csv
into data
folder
<- read_csv("data/hr96-21.csv",
hr na = ".")
5 inch height
,
7 inch width
, centered
, and figure resolution
is 72 dpi
"4 Candidates' election performance: 1996-2021"
as
captionR code
is not shown as output, but you
need to type it as chunk option{r, fig.height = 5, fig.width = 7, fig.align = "center", dpi = 72, fig.cap = "4 Candidates' election performance: 1996-2021"}
|>
hr select(year, voteshare, name) |>
filter(name == "KISHIDA, FUMIO" | name == "TAKAICHI, SANAE"|
== "KONO, TARO"| name == "NODA, SEIKO") |>
name ggplot(aes(x = year,
y = voteshare,
colour = name,
linetype = name,
shape = name)) +
geom_point() +
geom_line() +
geom_text(
aes(y = voteshare + 0.1,
label = round(voteshare, digits = 1), vjust = 0)
+
) theme(legend.position = c(0.85, 0.2)) +
labs(x = "Election Year",
y = "Vote share(%)")
As explained in 3.1.14 Plot
, you can add a chunk
option inside of {r}
But, when you have a bunch of chuk options, it is not easy to
read to add many chunks inside of {r}
→ You can assign multiple chunk options using #|
In 3.1.14 Plot
, we assigned chunk options as
follows:
```{r, fig.height = 5, fig.width = 7, fig.align = "center",
dpi = 72, fig.cap = "4 Candidates' election performance: 1996-2021"}
```{r}
#| fig.height: 5
#| fig.width: 7
#| fig.align: "center"
#| dpi: 72
#| fig.cap: "4 Candidates' election performance: 1996-2021"
Rmd
file, declare as
follows:fig.align = "center" |
:Centering all figures | |
dpi = 300" |
:Setting figure resolution = 300 | |
→ You type YAML
header as follows:
```{r, include = FALSE}
knitr::opts_chunk$set(fig.align = "center", dpi = 300)
```
fig.align = "center"
& dpi = 300
)
covering all chunks in RMarkdown fileR code
with otherstidy = TRUE
tidy = TRUE
and the one with tidy = TRUE
R code
you typed in a chunk|>ggplot(aes(x=year,y=voteshare,colour=j_name)) hr
tidy = TRUE
in your chunk option|>ggplot(aes(x=year,y=voteshare,colour=j_name)) hr
tidy = TRUE
in your chunk option|>
hr ggplot(aes(x = year, y = voteshare, colour = j_name))
tidy = TRUE
in your chunk option enables you to
output way easy-to-read R code
tidy = TRUE
, you need to install a package,
{formatR
} beforehandlibrary(formatR)
on your Rmd fileR Markdown
file, you will see the
following header
on the top---
: "Untitled"
title: "Masahiko Asano"
author: "2022-09-13"
date: html_document
output---
・title
: Title of the Rmd file
・author
: Your name
・date
: Date you make this document
・output
: Type of output・・・ you type html
here
R Markdown
header is written by YAML
formatinline R code
in them・It would be useful for you to assign
date: "2022-10-03"
at date
section
→ You don’t have to type today’s date every time you work on your Rmd
file
Rmd file
(out of a chunk)---
: "How to use RMarkdown"
title: "Masahiko Asano"
author: "`r Sys.Date()`"
date: html_document
output---
html
outputtoc |
:Output of contents | default is FALSE |
toc_depth |
:Depth of contents | default is 3 |
toc_float |
:Floating contents | default is FALSE |
number_sections |
:Serial number | default is FALSE |
#
makes a chapter
##
makes a section
###
makes a sub-section
What you type in Rmd file
(out of a chunk)
---
: "title"
title: "sub-title"
subtitle: "Your name"
author: "`r Sys.Date()`"
date:
output:
html_document: FALSE
toc: 3 # The depth of toc = 3
toc_depth: FALSE # No floating contents
toc_float: FALSE # No serial numbers on contents
number_sections---
# 1. Making Regression Make Sense
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
## 1.1 Regression Fundamentals
yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy
yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy
## 1.2 Regression and Causality
zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz
html
outputR code
enhances readability of the
codehighligh:
R Markdown 2.3
enables us to choose from 10 kinds
highlightshighlight: "tango"
---
: ""
title: ""
subtitle: ""
author: "`r Sys.Date()`"
date:
output:
html_document: "tango" # You assign your preferable hyghlight here
highlight---
3.12 Comments
If you have written something interesting and important, but you will not use it for a while
→ It would be better for you to save it as a comment:
Use
<!--
and-->
What you type in
Rmd file
html
outputI write something below, but it is not didplayed
You cannot see the sentence above