Resul Umit
post-doctoral researcher at the University of Oslo
teaching and studying representation, elections, and parliaments
Resul Umit
post-doctoral researcher at the University of Oslo
teaching and studying representation, elections, and parliaments
teaching workshops, also on
Resul Umit
post-doctoral researcher at the University of Oslo
teaching and studying representation, elections, and parliaments
teaching workshops, also on
Using WordPress
opened just before starting my PhD in 2013, at wordpress.com
at first, with rare updates
then, with more frequent blogposts
Using R
migrated from WordPress in 2018
frustrations with blogposts based on data
blogdown
(Xie et al., 2021a) makes quantitative academic writing efficientrequired getting used to at every login
One full day, on how to create websites for academics with R
One full day, on how to create websites for academics with R
Based on personalising the example website of the Academic
theme, with two options
One full day, on how to create websites for academics with R
Based on personalising the example website of the Academic
theme, with two options
Designed for researchers with basic knowledge of R programming language
Academic outreach
Academic outreach
Public outreach
What do people see when they google your name?
What do people see when they google your name?
To leave you with a website
To leave you with a website
To make you aware what else is possible
Google
, and perseverance are all you needThis workshop does not cover
dynamic websites
Hugo
, as integrated into R by blogdown
This workshop does not cover
dynamic websites
Hugo
, as integrated into R by blogdown
structural (HMTL, CSS, or JavaScript) customisation
Hugo
theme is an optionThis workshop does not cover
dynamic websites
Hugo
, as integrated into R by blogdown
structural (HMTL, CSS, or JavaScript) customisation
Hugo
theme is an optionmulti-language or multi-author websites
Sit in groups of two
Sit in groups of two
Type, rather than copy and paste, the code that you will find on these slides
Sit in groups of two
Type, rather than copy and paste, the code that you will find on these slides
When you have a question
* These slides are, and will remain, available at https://resulumit.com/teaching/rbd_workshop.html.
01:00
ggplot(data = df, mapping = aes(x = wt, y = mpg, color = cyl)) + geom_point(size = 2) + scale_colour_gradient(name = "Cylinders", high = "#132B43", low = "#56B1F7", breaks = c(4, 6, 8)) + theme_bw() + theme(axis.title = element_text(size = 20), axis.text = element_text(size = 20), legend.title = element_text(size = 20), legend.text = element_text(size = 20)) + labs(x = "\nWeight", y = "Miles/Gallon\n")
typefont
.content/
is a directoryPart 1. Getting the Tools Ready
Part 1. Getting the Tools Ready
Git is a software that
Git is a software that
To get this software
GitHub is a hosting service, or a website, that
GitHub is a hosting service, or a website, that
To sign up for this service
Netlify is a hosting service that
Hugo
Netlify is a hosting service that
Hugo
To sign up for this service
R is a programming language that
R is a programming language that
Install the following R packages, using the code below
install.packages(c("blogdown", "dplyr", "ggplot2"))
blogdown
(Xie et al., 2021a), for creating websitesknitr
package (Xie, 2021), which we will use for tabling datadplyr
(Wickham et al., 2021), for data manipulationbase
, data.table
(Dowle & Srinivasan, 2021)ggplot2
(Wickham et al., 2020b), for plotting database
, plotly
(Sievert et al., 2021)blogdown
— Overviewblogdown
— OverviewHugo
for generating sitespandoc
for transforming Markdown files into HTMLYAML
syntaxes for configuration and front matterblogdown
— OverviewHugo
for generating sitespandoc
for transforming Markdown files into HTMLYAML
syntaxes for configuration and front matterblogdown
— OverviewHugo
for generating sitespandoc
for transforming Markdown files into HTMLYAML
syntaxes for configuration and front matterblogdown
— AddinsObserve that, after installing blogdown
, RStudio includes six new addins
Serve
Site
Each addin has a corresponding function
blogdown::serve_site()
* [*] Not all blogdown
functions are exported. In practice, this means we would need to call blogdown
::: (with the triple-colon operator) for some functions, such blogdown:::touch_file()
.
blogdown
— Important Fuctionsblogdown
provides functions to facilitate interacting with Hugo
from within R, includingblogdown::install_hugo()
blogdown::serve_site()
blogdown
functions with the double colon operator ::library(blogdown)
firstblogdown::
in the Console
tab
key on your keyboardHugo
— Install from within RStudioInstall Hugo
, with the following code
blogdown::install_hugo()
Hugo
is a static website generator
It comes with
Academic
themeR Markdown: The Definitive Guide (Xie et al., 2019)
R Markdown Cheat Sheet
Help -> Cheatsheets -> R Markdown Cheat Sheet
Pandoc User's Guide
R for Data Science (Wickham and Grolemund, 2019)
Academic
— OverviewA theme designed by George Cushen
demonstration website is live at https://themes.gohugo.io/theme/academic/
documentaion is available at https://wowchemy.com/docs/
Visit three demonstration websites
Pay attention to the similarities and differences
05:00
Academic
— Demonstration SiteBiography
, Experience
, Accomplishments
etc.Academic
— Demonstration SiteBiography
, Experience
, Accomplishments
etc.Demo
, Posts
, Projects
etc.Academic
— Demonstration SiteBiography
, Experience
, Accomplishments
etc.Demo
, Posts
, Projects
etc.Courses
Academic
— Demonstration SiteBiography
, Experience
, Accomplishments
etc.Demo
, Posts
, Projects
etc.Courses
Academic
— AdvantagesAcademic
— AdvantagesHugo
released v0.71.1 on Monday 25 May 2020, which broke the themeAcademic
got updated the next day with a fixAcademic
— AdvantagesHugo
released v0.71.1 on Monday 25 May 2020, which broke the themeAcademic
got updated the next day with a fixAcademic
— DisadvantagesComplicated
Academic
— DisadvantagesComplicated
Popular
Academic
— Disadvantages
File -> New Project -> New Directory -> Website using blogdown
Give your project a name with Directory Name
Choose a location for the project with Browse...
Dropbox
, are likely to cause warning/error messagesDropbox
yihui/hugo-lithium
GiTHubUserName/RepoName
wowchemy/starter-academic
Academic
themeCreate Project
to startObserve that the root directory* is now populated with files for the theme and the example website
[*] The root directory is the main directory of your website project. It is often referred with a single slash /. For example /config.yaml indicates that there is a file called config.yaml
directly under the root directory — e.i., it is not in any other sub-directory.
Observe that the root directory is now populated with files, including
/config.yaml
and other configuration files under /config/
Observe that the root directory is now populated with files, including
/config.yaml
, /config/
/content/
/content/
is a section of a website/content/post/
can be viewed at https://janejdoe.netlify.app/post/
/content/
Observe that the files under /content/
are typically Markdown files
.md
extension/content/
Observe that the files under /content/
are typically Markdown files
.md
extensionThese files have typically two sections
Observe that the root directory is now populated with files, including
/config.yaml
, /config/
/content/
/static/
static/media/
Hugo
does not transform the files in this folder while generating websitesHugo
websites follow more or less the same directory structure
Hugo
documentation for directory structure at https://gohugo.io/getting-started/directory-structure//config/
The structure, as well as other technical details, might change
Hugo
versionHugo
VersionSet blogdown.hugo.version
in /.Rprofile
to the latest Hugo
version that you have
Hugo
version in /.Rprofile
is often out of dateHugo
versions that you haveblogdown::find_hugo("all")
in the Console
.Rprofile
take affect only after saving the file, and restarting RSession -> Restart R
Serve
Site
Click the Addins
->
Serve
Site
to preview the site
blogdown::serve_site()
in the Console
Observe that the website is live in the Viewer
tab
Serve
Site
Click the Addins
->
Serve
Site
to preview the site
blogdown::serve_site()
in the Console
Observe that the website is live in the Viewer
tab
Serve Site
Click the Addins -> Serve Site
to preview the site
blogdown::serve_site()
in the Console
Observe that the website is live in the Viewer
tab
You can make live edits in this state
/config.yaml
, change title = "Academic", and saveThere are four configuration files in the theme
/config.yaml
/config/_default/languages.yaml
/config/_default/menus.yaml
/config/_default/params.yaml
There are four configuration files in the theme
/config.yaml
/config/_default/languages.yaml
/config/_default/menus.yaml
/config/_default/params.yaml
These files are for overall definitions, settings, and organisation
There are four configuration files in the theme
/config.yaml
/config/_default/languages.yaml
/config/_default/menus.yaml
/config/_default/params.yaml
These files are for overall definitions, settings, and organisation
We will work with the existing options of in these files
YAML uses key: value pairs
Hugo
, but also by each themetitle
title: "Jane J. Doe"
YAML uses key: value pairs
Hugo
, but also by each themetitle
Values can take
title: "Jane J. Doe"
* String do not need quotation marks unless they include special characters, such as a colon. Once I spent half a day trying to understand why my website would not build, only to figure this nuance out. I therefore recommend using quotations marks for all strings, just in case.
YAML uses key: value pairs
Hugo
, but also by each themetitle
Values can take
title: "Jane J. Doe" summaryLength: 30
YAML uses key: value pairs
Hugo
, but also by each themetitle
Values can take
title: "Jane J. Doe" summaryLength: 30 enableEmoji: true
YAML uses key: value pairs
Hugo
, but also by each themetitle
Values can take
title: "Jane J. Doe" summaryLength: 30 enableEmoji: true interests: - Party politics - Public policy - International polities
There is an alternative way to write sequence of values
title: "Jane J. Doe" summaryLength: 30 enableEmoji: true interests: [Party politics, Public policy, International polities]
Multiple nesting of keys and sequences is also possible
education: courses: - course: PhD in Political Science institution: University of Vienna year: 2017 - course: MSSc in European Studies institution: University of Tampere year: 2009
To disable an option in YAML, you can
# title: "Jane J. Doe"
To disable an option in YAML, you can
# title: "Jane J. Doe"
[]
title: []
To disable an option in YAML, you can
# title: "Jane J. Doe"
[]
title: []
title: ""
To disable an option in YAML, you can
# title: "Jane J. Doe"
[]
title: []
title: ""
/config.yaml
/config.yaml
filetitle
and copyright
* keys, withbaseurl
in this file* ©
is the HTML code for the copyright symbol ©. {year}
turns into the current year, so that you don't have to update this every year.
05:00
params.yaml
params.yaml
file/config/_default/
Scroll through the other keys in other sections
15:00
menus.yaml
This file configures the website menu
menus.yaml
name
argumentmain - name: "Posts" - name: "Courses" - name: "Twitter" - name: "CV"
menus.yaml
weight
argument
main - name: "Posts" weight: 10 - name: "Courses" weight: 30 - name: "Twitter" weight: 20 - name: "CV" weight: 40
menus.yaml
url
argument/content/home/
/content/
/static/
sub-directoryfiles/cv.pdf
suggests cv is under /static/files/cv.pdf
main: - name = "Posts" weight = 10 url = "#posts" - name = "Courses" weight = 30 url = "courses/" - name = "Twitter" weight = 20 url = "https://twitter.com/resulumit" - name = "CV" weight = 40 url = "files/cv.pdf"
menus.yaml
Edit the menus.yaml
file, as much as possible now*
* You are likely to edit this file throughout the workshop, as your website evolves.
05:00
languages.yaml
This file
defines the language of the website
can make the site multi-lingual
Strategy
languages.yaml
This exercise is optional
Change the langauge of your website, in two steps
languages.yaml
: languageCode
key
/config.yaml
:defaultContentLanguage
03:00
Structure depends mostly on the way the /content/
directory is organised, including
Each page at the fronted corresponds to a Markdown file at the backend
Sections are organised in separate directories under /content/
content/post/
is a section (for all blogposts)_index.md
under the second-level directoryA website with a single page
.└── /content/ | └── home.md # <- https://janejdoe.netlify.app/home/
A website with two single pages
.└── /content/ | ├── home.md # <- https://janejdoe.netlify.app/home/ | └── about.md # <- https://janejdoe.netlify.app/about/
A website with five pages
.└── /content/ | ├── home.md # <- https://janejdoe.netlify.app/home/ | ├── about.md # <- https://janejdoe.netlify.app/about/ | └── blog/ # <- https://janejdoe.netlify.app/blog/ | ├── first-post.md # <- https://janejdoe.netlify.app/blog/first-post/ | └── second-post.md # <- https://janejdoe.netlify.app/blog/second-post/
Note that there are
A website with three pages
.└── /content/ | ├── home.md # <- https://janejdoe.netlify.app/home/ | ├── about.md # <- https://janejdoe.netlify.app/about/ | └── blog/index.md # <- https://janejdoe.netlify.app/blog/
Note that
index.md
is a special file name for Hugo
— it creates a page matching its directory nameA website with five pages: three three single pages and two nested section pages
.└── /content/ | ├── home.md # <- https://janejdoe.netlify.app/home/ | └── blog/ # <- https://janejdoe.netlify.app/blog/ | ├── first-post.md # <- https://janejdoe.netlify.app/blog/first-post/ | └── academic/ # <- https://janejdoe.netlify.app/blog/academic/ | ├── _index.md | └── second-post.md # <- https://janejdoe.netlify.app/blog/academic/second-post/
A website with five pages: three single pages and two nested section pages
.└── /content/ | ├── home.md # <- https://janejdoe.netlify.app/home/ | └── blog/ # <- https://janejdoe.netlify.app/blog/ | ├── first-post.md # <- https://janejdoe.netlify.app/blog/first-post/ | └── academic/ # <- https://janejdoe.netlify.app/blog/academic/ | ├── _index.md | └── second-post.md # <- https://janejdoe.netlify.app/blog/academic/second-post/
A website with five pages: three single pages and two nested section pages
.└── /content/ | ├── home.md # <- https://janejdoe.netlify.app/home/ | └── blog/ # <- https://janejdoe.netlify.app/blog/ | ├── first-post.md # <- https://janejdoe.netlify.app/blog/first-post/ | └── academic/ # <- https://janejdoe.netlify.app/blog/academic/ | ├── _index.md | └── second-post.md # <- https://janejdoe.netlify.app/blog/academic/second-post/
A website with five pages: three single pages, two nested section pages
.└── /content/ | ├── home.md # <- https://janejdoe.netlify.app/home/ | └── blog/ # <- https://janejdoe.netlify.app/blog/ | ├── first-post.md # <- https://janejdoe.netlify.app/blog/first-post/ | └── academic/ # <- https://janejdoe.netlify.app/blog/academic/ | ├── _index.md | └── second-post.md # <- https://janejdoe.netlify.app/blog/academic/second-post/
Notice that
_index.md
, with underscore, is a special file name for Hugo
— it creates sectionsHaving _index.md
in first-order sub-directories is optional, but may be helpful
publication/
is titled as Publications
_index.md
.└── /content/ | └── home.md # <- https://janejdoe.netlify.app/home/ | └── about.md # <- https://janejdoe.netlify.app/about/ | └── blog/ # <- https://janejdoe.netlify.app/blog/ | ├── _index.md | ├── first-post.md # <- https://janejdoe.netlify.app/blog/first-post/ | └── second-post.md # <- https://janejdoe.netlify.app/blog/second-post/
Explore the directory structure of your website in RStudio
courses/
Do a matching exercise
/content/publication/journal-article/index.md
05:00
home/
— OverviewThe homepage in Academic
does not exactly follow the structure above
home/
is not a stand alone pagehome/
— OverviewThe homepage in Academic
does not exactly follow the structure above
home/
is not a stand alone pageWidgets are complicated Markdown files
contact.md
widget gets the address information from params.yaml
home/
— OverviewThe homepage in Academic
does not exactly follow the structure above
home/
is not a stand alone pageWidgets are complicated Markdown files
contact.md
widget gets the address information from params.yaml
A homepage can have one, more, or all widgets
home/
— WidgetsThere are 13 types of pre-defined widgets
home/
— WidgetsThere are 13 types of pre-defined widgets
Widgets are in fact Markdown files, with .md extension
demo.md
home/
— WidgetsThere are 13 types of pre-defined widgets
Widgets are in fact Markdown files, with .md extension
demo.md
Widgets are located under /content/home/
index.md
, each file is a widget — some duplicates of the same typeSome keys are common across all widgets
widget: "pages"
Some keys are common across all widgets
widget: "pages" active: false
Some keys are common across all widgets
widget: "pages" active: false weight: 9
Some keys are common across all widgets
widget: "pages" active: false weight: 9 title: "Recent Publications" subtitle: ""
Some keys are common across all widgets
Some keys are widget specific
widget: "pages" active: false weight: 9 title: "Recent Publications" subtitle: "" page_type: "publication"
Some keys are common across all widgets
Some keys are widget specific
Widgets in the example site come with many keys and detailed definitions
widget: "pages" active: false weight: 9 title: "Recent Publications" subtitle: "" page_type: "publication"
There are at least three ways to add new pages and sections
Hugo
and Academic
Rename one or more blogposts and publications on your website
Hint:
10:00
There are at least two ways to remove pages and sections
Hugo
and Academic
/content/authors/
admin
(main) and 吳恩達
(secondary)Keep only the widgets that you would like to have on your website
Hint:
/content/home/index.md
is not a widget/config/_default/menus.yaml
10:00
You can deactivate a specific page in a section
/content/publication/journal-article/index.md
You can deactivate whole sections in one go
/content/publication/_index.md
You can deactivate whole sections except one or more pages
/content/publication/_index.md
/content/publication/journal-article/index.md
Not all sections have _index.md
to start with
/content/project/
File -> New File -> R Script
Draft pages and sections are still visible to you in live preview
blogdown::serve_site
Keep only the sections and pages that you would like to have on your website
draft
key to true
or false
in the front matter of relevant filesHint:
admin
is the only author/config/_default/menus.yaml
10:00
Deployment of your website onto a web server makes it visible online
You can deploy your website at any web server that you prefer
blogdown
package and the Academic
themeDeployment occurs in two steps
we push the website files, from our computer, into a GitHub repository
Netlify does the rest automatically, in a minute or so
Hugo
push
push
push
Working with with Git and GitHub requires
[*] We have started this process already, in Part 1 of the workshop, by downloading and installing Git and signing up for GitHub.
1) Enable version control with RStudio
Tools -> Global Options -> Git/SNV -> Enable version control interface for RStudio projects
RStudio will likely find Git automatically. In case it cannot, Git is likely to be at
c:/Program Files/Git/bin/git.exe
on Windows
/usr/local/git/bin/git
on Mac
2) Set Git Bash as your shell (Windows-only step)
Tools -> Global Options -> Terminal -> New terminals open with: Git Bash
3) Introduce yourself to Git
Tools -> Terminal -> New Terminal
git config --global user.name "YOUR NAME" git config --global user.email "YOUR EMAIL ADDRESS"
git config --global --list
1) Initiate local version control with Git
Tools -> Version Control -> Project Setup... -> Version Control System -> Git
after confirming your new repository, and restarting the session, observe that
.gitignore
file2) Create a new GitHub repository
Repositories -> New -> Repository name (e.g., "my_website") -> Public -> Create repository
observe that
repository URLs have the following structure: https://github.com/USER_NAME/REPOSITORY_NAME
Terminal
, the address gets the .git
extension
3) Push an existing repository
Tools -> Terminal -> New Terminal
Terminal
git remote add origin https://github.com/USER_NAME/REPOSITORY_NAME.gitgit add .git commit -m "initial commit"git push -u origin master
1) After logging in to Netlify, follow
New site from Git -> GitHub
Deploy site
2) While on the Site overview
page, click on Domain settings
Add custom domain
and follow the instructionsOptions
to change the random address to something more meaningful1) In RStudio, edit your site with the its URL
baseurl
key in /config.yaml
https://yournamesurname.netlify.app/
2) Commit and Push
M
, for modified, as Status
Staged
* for that file, and click Commit
Commit message
that summarises the editCommit
to create a record of the new version locally to your computerClose -> Push
to push the version to GitHub[*] To stage is to add files to be committed. It allows us to commit one or more files together or separately.
blogdown
for your advantage, observe it in Viewerblogdown
for your advantage, observe it in Viewergit checkout HEAD PATH/TO/FOLDER/OR/FILE
reverts a specific folder or filegit reset --hard
reverts allblogdown
for your advantage, observe it in Viewergit checkout HEAD PATH/TO/FOLDER/OR/FILE
reverts a specific folder or filegit reset --hard
reverts allPractice deployment one more time
title
key in /config.yaml
03:00
Most of what is visible at website frontend is stored in three directories at the backend
/assets/
directory/static/
directory/content/
directory/assets/
Hugo
to generate the website
/assets/
do not have a matching URL/assets/
is straightforwardAcademic
looks in /assets/media/
for a website iconicon.png
Academic
uses the default icon/assets/
Change your website icon
icon.png
to /assets/media/
Hint:
03:00
/static/
Hugo
simply copies these files over to frontend/static/
Hugo
simply copies these files over to frontend
/static/
have a matching URL.└── /static/ | └── pfofile-photo.jpg # <- https://janejdoe.netlify.app/pfofile-photo.jpg | └── files/ | └── cv.pdf # <- https://janejdoe.netlify.app/files/cv.pdf
/static/
Hugo
simply copies these files over to frontend
/static/
have a matching URL/static/
is straightforward/static/
is the right directory to store PDFs/static/
Make one or more files available as-is on your website
/static/
Hint:
05:00
/content/
This directory stores mostly textual files to be processed
Hugo
, some by blogdown
Most files under this directory are plain Markdown files
.md
extensionBlackfriday
— Hugo
's Markdown rendering engine, so is Netlify's — into HTMLblogdown
, but cannot execute any codeSome are R Markdown files
.Rmd
or .Rmarkdown
extensionpandoc
— blogdown
's rendering engineblogdown
Markdown is a plain-text file
Markdown is a plain-text file
Plain Markdown (.md
) follows Blackfriday
's Markdown syntax
Blackfriday
-specific extensions are available at https://github.com/russross/blackfridayR Markdown (.Rmd
and .Rmarkdown
) follows the syntax in Pandoc's Markdown
There are at least two different strategies to deal with .md
versus .Rmd
dilemma
use .md
for pages with no data, .Rmd
for pages with data
use .Rmd
for all pages
.md
There are at least two different strategies to deal with .md
versus .Rmd
dilemma
use .md
for pages with no data, .Rmd
for pages with data
use .Rmd
for all pages
.md
The syntax in the following slides of this section will work with both types
Multiple spaces on a given line are reduced to one
This is a sentence followed by four spaces. This is another sentence on the same line.
This is a sentence followed by four spaces. This is another sentence on the same line.
Line endings with fewer than two spaces are ignored
This is a sentence followed by one space.This is another sentence on a new line.
This is a sentence followed by one space. This is another sentence on a new line.
Two or more spaces at the end of lines introduce hard brakes, forcing a new line
This is a sentence followed by two spaces. This is another sentence on a new line.
This is a sentence followed by two spaces.
This is another sentence on a new line.
Lines starting with the grater-than sign > introduce block quotes
> In God, we trust. All others must bring data. >> --- Anonymous
In God, we trust. All others must bring data.
— Anonymous
One or more* blank lines introduce a new paragraph
This is the first sentence of a paragraph as it is preceded by a blank line. This is the second sentence of that paragraph, which is followed by a blank line. This is the first sentence of a *new paragraph* as it is preceded by a blank line. This is the second sentence of that paragraph, which is followed by a blank line.
This is the first sentence of a paragraph as it is preceded by a blank line. This is the second sentence of that paragraph, which is followed by a blank line.
This is the first sentence of a new paragraph as it is preceded by a blank line. This is the second sentence of that paragraph, which is followed by a blank line.
[*] Multiple blank lines between paragraphs reduced to one.
Text with the syntax <!--comments --> is omitted from output
<!-- This paragraph needs re-writing -->This is the first sentence of a paragraph as it is preceded by a blank line. This is the second sentence of that paragraph, which is followed by a blank line. This is the first sentence of a new paragraph <!-- I've removed italics --> as it is preceded by a blank line. This is the second sentence of that paragraph, which is followed by a blank line.
This is the first sentence of a paragraph as it is preceded by a blank line. This is the second sentence of that paragraph, which is followed by a blank line.
This is the first sentence of a new paragraph as it is preceded by a blank line. This is the second sentence of that paragraph, which is followed by a blank line.
The number sign # introduces headers; lower levels are created with additional signs — up to total five levels
# Introduction becomes
## 1. Introduction becomes
### 3.1 Introduction becomes
#### Introduction becomes
##### Introduction becomes
A pair of single asterisk * or underscore _ introduces italics
*italics* becomes italics
_italics_ becomes italics as well
A pair of double asterisks or underscores introduces bold
**bold** becomes bold
__bold__ becomes bold as well
These two rules can be combined
**_bolditalics_** becomes boldsitalics
_**bolditalics**_ becomes bolditalics as well
A pair of double tildes ~ introduces strikethrough
~~strikethrough~~ becomes strikethrough
Strikethrough can be combined with italics or bold
**~~strikebold~~** or __~~strikebold~~__, they both become strikebold
~~**strikebold**~~ or ~~__strikebold__~~, they both become strikebold as well
*~~strikeitalitcs~~* or _~~strikeitalitcs~~_, they both become strikeitalitcs
~~*strikeitalitcs*~~ or ~~_strikeitalitcs_~~, they both become strikeitalitcs as well
You can link text to section headers in the same document
[Conclusion](#conclusion) becomes Conclusion, and a click takes the screen to that section
Multi-word headers need hyphenation
[Literature Review](#literature-review) becomes Literature Review, and it works only if the second part is hyphenated
[*] We will cover links to references, figures, and tables later on.
You can link text to URLs
[click here](https://janejdoe.netlify.app/) becomes click here
<https://janejdoe.netlify.app> becomes https://janejdoe.netlify.app
[https://janejdoe.netlify.app](https://janejdoe.netlify.app/) becomes
https://janejdoe.netlify.app as well
You can link text to URLs
[click here](https://janejdoe.netlify.app/) becomes click here
<https://janejdoe.netlify.app> becomes https://janejdoe.netlify.app
[https://janejdoe.netlify.app](https://janejdoe.netlify.app/) becomes
https://janejdoe.netlify.app as well
You can also link text to email addresses
[email me](mailto:j.j.doe@kriens.edu)* becomes email me
<j.j.doe@kriens.edu> becomes j.j.doe@kriens.edu
[*] Notice the prefix mailto: in the second part of the construct
Use the [^identifier] syntax, with identifiers defined elsewhere in the same document, to create a footnote
Dr Doe holds a PhD in rock science.[^1][^1]: She defended her thesis in 2017.
Dr Doe holds a PhD in rock science.1
[1] She defended her thesis in 2017.
Lines starting with asterisk * as well as plus + or minus − signs introduce lists
- books- articles- reports
Lists can be nested within each other, with indentation
+ books+ articles - published - under review + revised and resubmitted - work in progress
List items can be numbered
1. books2. articles - published - under review + revised and resubmitted - work in progress
List items can be numbered
1. books2. articles - published - under review + revised and resubmitted - work in progress
Task lists can be created in plain Markdown, but not in R Markdown
- [x] books- [ ] articles - [ ] published - [x] under review + [x] revised and resubmitted - [ ] work in progress
Two hyphens grouped together introduce an en-dash
‐‐ becomes –
Three hyphens grouped together introduce an em-dash
‐‐‐ becomes —
Highlight any piece of text, by putting it in between a pair of backticks `
`code`
becomes code
Highlight any piece of text, by putting it in between a pair of backticks `
`code`
becomes code
Highlight blocks of text by putting them in between two lines, each starting with three backticks ```
```df <- mtcars %>% filter(gear > 3)```
becomes
df <- mtcars %>% filter(gear > 3)
The following syntax introduces hand-made tables
|First Column | Second Column | |------------ | ------------- ||First cell | First cell | |Second cell | Second cell ||Third cell | Third cell |
First Column | Second Column |
---|---|
First cell | First cell |
Second cell | Second cell |
Third cell | Third cell |
The following syntax introduces hand-made tables
|First Column | Second Column | |------------ | ------------- ||First cell | First cell | |Second cell | Second cell ||Third cell | Third cell |
First Column | Second Column |
---|---|
First cell | First cell |
Second cell | Second cell |
Third cell | Third cell |
Note that
The syntax  embeds images into HTML outputs
[*] If the image is in static/
, use a path relative to that directory, e.g., 

image
keyfeatured.jpg
image
key in YAML is not effective Edit one or more Markdown files in your website project
Hint, if you are re-creating JJD's website:
add and/or edit one or more of the following files
/content/home/hero.md
, matching this widget/content/author/admin/index.md
, matching this widget/content/blog/academic-websites/index.md
, matching this postby copy the text from the website to save time
30:00
.Rmd
or .Rmarkdown
extension.Rmd
or .Rmarkdown
extensionHugo
cannot transform R Markdown into HTMLblogdown
package.Rmd
or .Rmarkdown
extensionHugo
cannot transform R Markdown into HTMLblogdown
packageMost codes go inside code chunks
```{r}df <- mtcars %>% mutate(disp_litre = disp / 61.0237)```
Codes can also go in line with text
The average engine displacement of the cars in the dataset is `r mean(df$disp_litre)` litres.
```{r}```
```{r}```
r
is an option of the chunk, indicating that the code in the chunk above should be run by Rpython
, which we will not cover in this workshop```{r}```
r
is an option of the chunk, indicating that the code in the chunk above should be run by Rpython
, which we will not cover in this workshop[*] Depending on whether code chunks are displayed or not. See the echo
option in the following slides.
Label the code chunks right after r
```{r, tidydata}df <- mtcars %>% mutate(disp_litre = disp / 61.0237)```
Label the code chunks right after r
```{r, tidydata}df <- mtcars %>% mutate(disp_litre = disp / 61.0237)```
Note that
Code chunks take options, listed on the same line with the first delimiter, in curly brackets
setup
, and and the include
option is set to FALSE
```{r, tidydata, include=FALSE}```
The list of options is available at https://yihui.org/knitr/options
Options have default values
echo
, the default is TRUE
echo
: should the source code printed in the output? — yes```{r, tidydata}```
```{r, tidydata, echo=TRUE}```
This chunk prints two things in the output document — (a) the code and (b) the head of the data frame
```{r, headdata}head(df)```
head(df)
## mpg cyl disp hp drat wt qsec vs am gear carb disp_litre## Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4 2.621932## Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4 2.621932## Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1 1.769804## Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1 4.227866## Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2 5.899347## Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1 3.687092
Setting echo=FALSE prevents the code from being displayed in the output document
```{r, headdata, echo=FALSE}head(df)```
This chunk therefore prints one thing in the output document — the head of the data frame
## mpg cyl disp hp drat wt qsec vs am gear carb disp_litre## Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4 2.621932## Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4 2.621932## Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1 1.769804## Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1 4.227866## Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2 5.899347## Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1 3.687092
Prevent the result(s) of the source code from being displayed in the output document
```{r, headdata, results="hide"}head(df)```
This chunk therefore prints one thing in the output document — the source code
head(df)
Cache results for future compilations
```{r ... cache=TRUE}```
Cache results for future compilations
```{r ... cache=TRUE}```
Prevent R from running the code in the chunk altogether
```{r ... eval=FALSE}```
Cache results for future compilations
```{r ... cache=TRUE}```
Prevent R from running the code in the chunk altogether
```{r ... eval=FALSE}```
Prevent messages and/or warnings from being displayed in the output
```{r ... error=FALSE, message=FALSE, warning=FALSE}```
Define the actual dimensions of figures, in inches
```{r ... fig.height=6, fig.width=9}```
Define the actual dimensions of figures, in inches
```{r ... fig.height=6, fig.width=9}```
Define the size of figures in the output document, with out.width
and/or out.height
```{r ... out.width="50%"}```
Define the actual dimensions of figures, in inches
```{r ... fig.height=6, fig.width=9}```
Define the size of figures in the output document, with out.width
and/or out.height
```{r ... out.width="50%"}```
Define the alignment of figures — left
, right
, or center
```{r ... fig.align="center"}```
Define captions for figures
```{r ... fig.caption="A Scatter Plot"}```
Define captions for figures
```{r ... fig.caption="A Scatter Plot"}```
Set the resolution for figures
```{r ... dpi=300}```
Define captions for figures
```{r ... fig.caption="A Scatter Plot"}```
Set the resolution for figures
```{r ... dpi=300}```
Set extra options, which rmarkdown
will write into the <img />
tag
```{r ... out.extra='style="display:block;"'}```
It is recommended to use the first code chunk for general setup, where you can
knitr::opts_chunk$set()
```{r, setup, include=FALSE}# chunk option defaultsknitr::opts_chunk$set(echo=FALSE, message=FALSE)# packageslibrary(dplyr)library(ggplot2)library(knitr)# datadf_raw <- mtcars```
Note that the data source can be anywhere that R can access
```{r, setup, include=FALSE}...# this dataset is available onlinedf_online <- read.csv("http://www.parlgov.org/static/data/development-cp1252/view_party.csv")# this dataset is in the same directory as my .Rmd filedf_local <- read.csv("view_cabinet.csv")```
I recommend using the second chunk for the main operations* on raw data
```{r, data, echo=FALSE ...}df <- df_raw %>% mutate(disp_litre = disp / 61.0237)```
Code can also be incorporated in text, with the `r `
syntax
If we multiply _pi_ by 5, we get `r pi * 5`.
If we multiply pi by 5, we get 15.7079633.
The average the engine displacement of the cars in the dataset is `r mean(df$disp_litre)` litres, which would round to `r round(mean(df$disp_litre), digits = 1)`.
The average the engine displacement of the cars in the dataset is 3.7808569, which would round to 3.8.
__Only `r nrow(subset(df, gear == 5))` cars__ in the dataset have five forward gears.
Only 5 cars in the dataset have five forward gears.
Place code that produces figures in code chunks
```{r, scatterplot, fig.cap = "A scatterplot of cars.", echo=FALSE}ggplot(data = df, mapping = aes(x = wt, y = mpg, color = cyl)) + geom_point() + scale_colour_gradient(name = "Cylinders", high = "#132B43", low = "#56B1F7", breaks = c(4, 6, 8)) + labs(x = "Weight", y = "Miles/Gallon") + theme_bw()```
Figure 1. A scatterplot of cars.
Use the following syntax to refer to figures
See Figure \@ref(fig:scatterplot) below.
```{r, scatterplot, fig.cap = "A scatterplot of cars.", echo=FALSE}ggplot(data = df, mapping = aes(x = wt, y = mpg, color = cyl)) + geom_point() + scale_colour_gradient(name = "Cylinders", high = "#132B43", low = "#56B1F7", breaks = c(4, 6, 8)) + labs(x = "Weight", y = "Miles/Gallon") + theme_bw()```
Place code that produces HTML tables in code chunks
```{r, headdata, echo=FALSE}kable(head(df, 3), caption = "First three rows in the dataset")```
mpg | cyl | disp | hp | drat | wt | qsec | vs | am | gear | carb | disp_litre | |
---|---|---|---|---|---|---|---|---|---|---|---|---|
Mazda RX4 | 21.0 | 6 | 160 | 110 | 3.90 | 2.620 | 16.46 | 0 | 1 | 4 | 4 | 2.621932 |
Mazda RX4 Wag | 21.0 | 6 | 160 | 110 | 3.90 | 2.875 | 17.02 | 0 | 1 | 4 | 4 | 2.621932 |
Datsun 710 | 22.8 | 4 | 108 | 93 | 3.85 | 2.320 | 18.61 | 1 | 1 | 4 | 1 | 1.769804 |
Table 1. First three rows in the dataset.
Use the following syntax to refer to tables
See Table \@ref(tab:headdata) below.
```{r, headdata, echo=FALSE}kable(head(df, 3), caption = "First three rows in the dataset")```
See Table 1 below.
mpg | cyl | disp | hp | drat | wt | qsec | vs | am | gear | carb | disp_litre | |
---|---|---|---|---|---|---|---|---|---|---|---|---|
Mazda RX4 | 21.0 | 6 | 160 | 110 | 3.90 | 2.620 | 16.46 | 0 | 1 | 4 | 4 | 2.621932 |
Mazda RX4 Wag | 21.0 | 6 | 160 | 110 | 3.90 | 2.875 | 17.02 | 0 | 1 | 4 | 4 | 2.621932 |
Datsun 710 | 22.8 | 4 | 108 | 93 | 3.85 | 2.320 | 18.61 | 1 | 1 | 4 | 1 | 1.769804 |
Table 1. First three rows in the dataset.
The following syntax, outside code chunks, introduces tables*
First Column Second Column ------------ ------------- First cell First cell Second cell Second cell Third cell Third cell
First Column | Second Column |
---|---|
First cell | First cell |
Second cell | Second cell |
Third cell | Third cell |
* The table syntax on this and following seven slides will work in R Markdown files only — they will not work in plain Markdown.
The position of headers, relative to their line underneath, defines column alignments
Left-Aligned Centered ---------------- ----------------First cell First cell Second cell Second cell Third cell Third cell
Left-Aligned | Centered |
---|---|
First cell | First cell |
Second cell | Second cell |
Third cell | Third cell |
A line starting with a colon, placed before or after tables, introduces captions
Centered Right-Aligned ---------------- ----------------First cell First cell Second cell Second cell Third cell Third cell : A hand-made table with R Markdown
Centered | Right-Aligned |
---|---|
First cell | First cell |
Second cell | Second cell |
Third cell | Third cell |
The caption line itself needs to be surrounded by empty lines
Centered Right-Aligned ---------------- ----------------First cell First cell Second cell Second cell Third cell Third cell : A hand-made table with R Markdown
Centered | Right-Aligned |
---|---|
First cell | First cell |
Second cell | Second cell |
Third cell | Third cell |
Tables are numbered automatically
: A hand-made table with R Markdown Centered Right-Aligned ---------------- ----------------First cell First cell Second cell Second cell Third cell Third cell
Centered | Right-Aligned |
---|---|
First cell | First cell |
Second cell | Second cell |
Third cell | Third cell |
Grid tables, with the following syntax, can handle complex cells with multiple lines and/or lists
+--------------------+--------------------+| First Column | Second Column | +====================+====================+| - First item | First cell | | - Second item | | | - Third item | |+--------------------+--------------------+|Second cell | Second cell with a | | | long text | +--------------------+--------------------+| Third cell | Third cell | | | | +--------------------+--------------------+: A grid table with multi-line cells
First Column | Second Column |
---|---|
- First item - Second item - Third item |
First cell |
Second cell | Second cell with a long text |
Third cell | Third cell |
Grid tables can be aligned as well, with colons at the boundaries of the header separator*
+--------------------+--------------------+| Left-Aligned | Centered | +:===================+:==================:+| - First item | First cell | | - Second item | | | - Third item | |+--------------------+--------------------+|Second cell | Second cell with a | | | long text | +--------------------+--------------------+| Third cell | Third cell | | | | +--------------------+--------------------+: A grid table with multi-line cells
Left-Aligned | Centered |
---|---|
- First item - Second item - Third item |
First cell |
Second cell | Second cell with a long text |
Third cell | Third cell |
* Use := for left-aligned, :=: for centered, =: for right-aligned columns.
Use the following syntax to refer to hand-made tables
See Table \@ref(tab:handmade) below.
Centered Right-Aligned ---------------- ----------------First cell First cell Second cell Second cell Third cell Third cell : (\#tab:handmade) A hand-made table with R Markdown
See Table 1 below.
Centered | Right-Aligned |
---|---|
First cell | First cell |
Second cell | Second cell |
Third cell | Third cell |
Add and/or edit one or more R Markdown files in your website project
Hint, if you are re-creating JJD's website:
add and edit the following file
/content/post/cabinet-size/index.Rmd
, matching this blogpostby copy the text from the website to save time
30:00
Dowle, M. and Srinivasan, A. (2021). data.table: Extension of 'data.frame'. R package, version 1.14.0.
Sievert, C., Parmer, C., Hocking, T., Chamberlain, S., Ram, K., Corvellec, M., & Despouy, P. (2021). plotly: Create Interactive Web Graphics via 'plotly.js'. R package, version 4.9.3.
Wickham, H. and Grolemund, G. (2019). R for data science. O'Reilly. Open access at https://r4ds.had.co.nz.
Wickham, H., Chang, W., Henry, L., Pedersen, T. L., Takahashi, K., Wilke, C., Woo, K., Yutani, H. and Dunnington, D. (2021). dplyr: A grammar of data manipulation. R package, version 1.0.5.
Wickham, H., François, W., Henry L. and Müller, K. (2020). ggplot2: Create elegant data visualisations using the grammar of graphics. R package, version 3.3.3.
Xie, Y. (2021). knitr: A general-purpose package for dynamic report generation in R. R package, version 1.33.
Xie, Y., Dervieux, C., and Hill, A. P. (2021a). blogdown: Create blogs and websites with R Markdown. R package, version 1.3.
Xie, Y., Thomas, A., and Hill, A. P. (2021b). blogdown: Creating Websites with R Markdown. Open access at https://bookdown.org/yihui/blogdown.
Resul Umit
post-doctoral researcher at the University of Oslo
teaching and studying representation, elections, and parliaments
Keyboard shortcuts
↑, ←, Pg Up, k | Go to previous slide |
↓, →, Pg Dn, Space, j | Go to next slide |
Home | Go to first slide |
End | Go to last slide |
Number + Return | Go to specific slide |
b / m / f | Toggle blackout / mirrored / fullscreen mode |
c | Clone slideshow |
p | Toggle presenter mode |
t | Restart the presentation timer |
?, h | Toggle this help |
Esc | Back to slideshow |