+ - 0:00:00
Notes for current slide
Notes for next slide

Creating Academic Websites with R


Resul Umit

April 2021

Skip intro — To the contents slide.                                                        I can teach this workshop at your institution — Email me.

1 / 177

Who am I?

Resul Umit

  • post-doctoral researcher at the University of Oslo

  • teaching and studying representation, elections, and parliaments

    • a recent publication: Parliamentary communication allowances do not increase electoral turnout or incumbents’ vote share
2 / 177

Who am I?

Resul Umit

  • post-doctoral researcher at the University of Oslo

  • teaching and studying representation, elections, and parliaments

    • a recent publication: Parliamentary communication allowances do not increase electoral turnout or incumbents’ vote share


2 / 177

Who am I?

Resul Umit

  • post-doctoral researcher at the University of Oslo

  • teaching and studying representation, elections, and parliaments

    • a recent publication: Parliamentary communication allowances do not increase electoral turnout or incumbents’ vote share



2 / 177

My First Website

Using WordPress

  • opened just before starting my PhD in 2013, at wordpress.com

  • at first, with rare updates

    • none based on data
    • required getting used to at every login
      • a system that I used only for my website
  • then, with more frequent blogposts

    • frustrations with posts based on data
      • slow to write and edit

    • still required getting used to at every login
3 / 177

My Current Website

Using R

  • migrated from WordPress in 2018

  • frustrations with blogposts based on data

    • slow to write and edit
    • blogdown (Xie et al., 2021a) makes quantitative academic writing efficient
  • required getting used to at every login

    • a system used only for website updates
    • a system that I use everyday for other tasks
      • cleaning and analysing data, writing results for publication
4 / 177

The Workshop — Overview

  • One full day, on how to create websites for academics with R

    • building a minimal working site
    • version-controlling and deploying it
    • adding new content to the site
5 / 177

The Workshop — Overview

  • One full day, on how to create websites for academics with R

    • building a minimal working site
    • version-controlling and deploying it
    • adding new content to the site


* I will refer to this demonstration as JJD's website here, to distinguish it from the example website of the theme.

5 / 177

The Workshop — Overview

  • One full day, on how to create websites for academics with R

    • building a minimal working site
    • version-controlling and deploying it
    • adding new content to the site



  • Designed for researchers with basic knowledge of R programming language

    • ability to work with R and RStudio will be very helpful
      • but not absolutely necessary — these skills can be developed after the workshop as well
6 / 177

The Workshop — Motivations

  • Academic outreach

    • make your work easily accessible to other academics
    • keep all academic work at one address
    • offer versions without paywall
      • e.g., pre-prints
7 / 177

The Workshop — Motivations

  • Academic outreach

    • make your work easily accessible to other academics
    • keep all academic work at one address
    • offer versions without paywall
      • e.g., pre-prints


  • Public outreach

    • make your work easily accessible to non-academics, in two senses
    • by removing paywalls
      • e.g., pre-prints

    • by writing for non-academic audience in mind
      • e.g., blogposts
7 / 177

The Workshop — Motivations — Impression Management

  • What do people see when they google your name?

    • google your name now, and scroll through
      • is this exactly what you want people to see?
8 / 177

The Workshop — Motivations — Impression Management

  • What do people see when they google your name?

    • google your name now, and scroll through
      • is this exactly what you want people to see?


  • Websites are an impression management tool

    • manage your online presence yourself
      • otherwise, others --- e.g., your (past and present) university --- will

    • provide a concrete example of your skills
      • e.g., working with R, Git
8 / 177

The Workshop — Aims

  • To leave you with a website

    • working, continuously deployed from RStudio
    • albeit minimal and/or mock
9 / 177

The Workshop — Aims

  • To leave you with a website

    • working, continuously deployed from RStudio
    • albeit minimal and/or mock


  • To make you aware what else is possible

    • so that you can update your website after the workshop
    • awareness of what is possible, Google, and perseverance are all you need
9 / 177

The Workshop — Limitations

This workshop does not cover

  • dynamic websites

    • it covers static websites, as generated by Hugo, as integrated into R by blogdown
      • all visitors see the same website, as last generated
      • this setting offers what most academics would need
10 / 177

The Workshop — Limitations

This workshop does not cover

  • dynamic websites

    • it covers static websites, as generated by Hugo, as integrated into R by blogdown
      • all visitors see the same website, as last generated
      • this setting offers what most academics would need
  • structural (HMTL, CSS, or JavaScript) customisation

    • e.g., changing the entire appearance and functionality of a theme, writing a new one
    • switching to another Hugo theme is an option
10 / 177

The Workshop — Limitations

This workshop does not cover

  • dynamic websites

    • it covers static websites, as generated by Hugo, as integrated into R by blogdown
      • all visitors see the same website, as last generated
      • this setting offers what most academics would need
  • structural (HMTL, CSS, or JavaScript) customisation

    • e.g., changing the entire appearance and functionality of a theme, writing a new one
    • switching to another Hugo theme is an option
10 / 177

The Workshop — Organisation

  • Sit in groups of two

    • participants learn as much from their partner as from instructors
    • play the role of co-authors
11 / 177

The Workshop — Organisation

  • Sit in groups of two

    • participants learn as much from their partner as from instructors
    • play the role of co-authors


  • Type, rather than copy and paste, the code that you will find on these slides

    • typing is a part of the learning process
    • but do copy the text from JJD's website, if you are re-creating it
11 / 177

The Workshop — Organisation

  • Sit in groups of two

    • participants learn as much from their partner as from instructors
    • play the role of co-authors


  • Type, rather than copy and paste, the code that you will find on these slides

    • typing is a part of the learning process
    • but do copy the text from JJD's website, if you are re-creating it


  • When you have a question

    • ask your partner
    • google together
    • turn your microphone on and ask, or
    • type it in the chat
11 / 177

The Workshop — Organisation — Slides*

  • Slides with this background colour indicate that your action is required, for
    • setting the workshop up
      • e.g., installing software

    • personalising the website
      • e.g., putting in your own contact details

    • completing the exercises
      • e.g., adding content to your website

  • Some of these slides have countdown timers
    • for guidance only

* These slides are, and will remain, available at https://resulumit.com/teaching/rbd_workshop.html.

01:00
12 / 177

The Workshop — Organisation — Slides

  • Codes and texts that go in as input appear as such — in a different font, on gray background
    • long codes and texts will have their own line(s)
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")
13 / 177

The Workshop — Organisation — Slides

  • Codes and texts that go in as input appear as such — in a different font, on gray background
    • long codes and texts will have their own line(s)


  • Results that come out as output appear as such — in the same font, on green background
    • except very obvious results, such as figures and tables
14 / 177

The Workshop — Organisation — Slides

  • Codes and texts that go in as input appear as such — in a different font, on gray background
    • long codes and texts will have their own line(s)


  • Results that come out as output appear as such — in the same font, on green background
    • except very obvious results, such as figures and tables


  • Specific sections are highlighted yellow as such for emphasis
    • these could be for anything — codes and texts in input, results in output, and/or texts on slides
14 / 177

The Workshop — Organisation — Slides

  • Codes and texts that go in as input appear as such — in a different font, on gray background
    • long codes and texts will have their own line(s)


  • Results that come out as output appear as such — in the same font, on green background
    • except very obvious results, such as figures and tables


  • Specific sections are highlighted yellow as such for emphasis
    • these could be for anything — codes and texts in input, results in output, and/or texts on slides


  • Names for items such as files, folders, variables are in typefont.
    • typefont with a trailing slash indicates a directory, known also as folder
      • e.g., content/ is a directory
14 / 177

The Workshop — Contents

Part 1. Getting the Tools Ready

  • e.g., installing software

Part 2. Website Front End

  • e.g., the look in a browser

Part 3. Website Back End

  • e.g., the look in RStudio

Part 4. Configuration

  • e.g., overall organisation and settings
15 / 177

The Workshop — Contents

Part 1. Getting the Tools Ready

  • e.g., installing software

Part 2. Website Front End

  • e.g., the look in a browser

Part 3. Website Back End

  • e.g., the look in RStudio

Part 4. Configuration

  • e.g., overall organisation and settings

Part 5. Managing Structure

  • e.g., organisation of pages and sections

Part 6. Deployment

  • e.g., publishing your website online

Part 7. Adding Content

  • e.g., adding text and images

Part 8. R Markdown

  • e.g., adding tables and figures
15 / 177

Part 1. Getting the Tools Ready

16 / 177

Git — Download from the Internet and Install

  • Git is a software that

    • keeps track of versions of a set of files
    • is local to you, the records are kept on your computer
    • is free
17 / 177

Git — Download from the Internet and Install

  • Git is a software that

    • keeps track of versions of a set of files
    • is local to you, the records are kept on your computer
    • is free


17 / 177

GitHub — Open an Account

  • GitHub is a hosting service, or a website, that

    • keeps a copy of the versions created by Git
    • is remote to you, like the Dropbox website
    • is, mostly, free
18 / 177

GitHub — Open an Account

  • GitHub is a hosting service, or a website, that

    • keeps a copy of the versions created by Git
    • is remote to you, like the Dropbox website
    • is, mostly, free


  • To sign up for this service

    • register an account at https://github.com
      • registering an account is free
      • usernames are public, editable
        • either choose an anonymous username for now
        • or choose one carefully — it becomes a part of users' online presence
18 / 177

Netlify — Open an Account

  • Netlify is a hosting service that

    • builds your website out of individual files, using Hugo
    • hosts your website on its servers, making it available online
    • is, mostly, free
19 / 177

Netlify — Open an Account

  • Netlify is a hosting service that

    • builds your website out of individual files, using Hugo
    • hosts your website on its servers, making it available online
    • is, mostly, free


  • To sign up for this service

    • register an account at https://www.netlify.com
      • registering an account is free
      • you can use your GitHub account to register
19 / 177

R and RStudio — Download from the Internet and Install

  • R is a programming language that

    • does or facilitates many things, e.g., creating a website
    • provides the engine for RStudio — an IDE, or dashboard
    • is free
20 / 177

R and RStudio — Download from the Internet and Install

  • R is a programming language that

    • does or facilitates many things, e.g., creating a website
    • provides the engine for RStudio — an IDE, or dashboard
    • is free



20 / 177

R Packages — Install from within RStudio

Install the following R packages, using the code below

install.packages(c("blogdown", "dplyr", "ggplot2"))


21 / 177

blogdown — Overview

  • A relatively small R package, to facilitate creating websites
    • enables a seamless workflow, all within RStudio
    • does not build websites itself
22 / 177

blogdown — Overview

  • A relatively small R package, to facilitate creating websites
    • enables a seamless workflow, all within RStudio
    • does not build websites itself
  • Builds upon other software
    • most importantly Hugo for generating sites
    • (R) Markdown for text formatting
    • pandoc for transforming Markdown files into HTML
    • YAML syntaxes for configuration and front matter
22 / 177

blogdown — Overview

  • A relatively small R package, to facilitate creating websites
    • enables a seamless workflow, all within RStudio
    • does not build websites itself
  • Builds upon other software
    • most importantly Hugo for generating sites
    • (R) Markdown for text formatting
    • pandoc for transforming Markdown files into HTML
    • YAML syntaxes for configuration and front matter
  • Has a confusing name
    • it is not necessarily about blogs, but general-purpose websites
22 / 177

blogdown — Overview

  • A relatively small R package, to facilitate creating websites
    • enables a seamless workflow, all within RStudio
    • does not build websites itself
  • Builds upon other software
    • most importantly Hugo for generating sites
    • (R) Markdown for text formatting
    • pandoc for transforming Markdown files into HTML
    • YAML syntaxes for configuration and front matter
  • Has a confusing name
    • it is not necessarily about blogs, but general-purpose websites
22 / 177

blogdown — Addins

  • Observe that, after installing blogdown, RStudio includes six new addins

    • e.g., Serve Site
    • mouse over in RStudio to read their definitions
  • Each addin has a corresponding function

    • e.g., 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().

23 / 177

blogdown — Important Fuctions

  • blogdown provides functions to facilitate interacting with Hugo from within R, including
    • blogdown::install_hugo()
    • blogdown::serve_site()


  • It is customary to call blogdown functions with the double colon operator ::
    • the usual way would also work
      • i.e., load library(blogdown) first


  • To see the list of exported functions, type blogdown:: in the Console
    • hit the tab key on your keyboard
24 / 177

Hugo — Install from within RStudio

Install Hugo, with the following code

blogdown::install_hugo()
  • Hugo is a static website generator

    • static websites are a collection of pages
    • pages display the same information to all visitors
  • It comes with

25 / 177

Other Resources — For Later

Help -> Cheatsheets -> R Markdown Cheat Sheet

26 / 177

Part 2. Website Frontend

27 / 177

Academic — Overview

28 / 177

Demonstration Sites

05:00
29 / 177

Academic — Demonstration Site

  • The homepage is composed of different parts, called widgets
    • e.g., the sections titled Biography, Experience, Accomplishments etc.
30 / 177

Academic — Demonstration Site

  • The homepage is composed of different parts, called widgets
    • e.g., the sections titled Biography, Experience, Accomplishments etc.


  • Some menu items direct the screen to different widgets on the homepage
    • e.g., Demo, Posts, Projects etc.
30 / 177

Academic — Demonstration Site

  • The homepage is composed of different parts, called widgets
    • e.g., the sections titled Biography, Experience, Accomplishments etc.


  • Some menu items direct the screen to different widgets on the homepage
    • e.g., Demo, Posts, Projects etc.


  • Other menu items direct to stand alone sections
    • e.g., Courses
30 / 177

Academic — Demonstration Site

  • The homepage is composed of different parts, called widgets
    • e.g., the sections titled Biography, Experience, Accomplishments etc.


  • Some menu items direct the screen to different widgets on the homepage
    • e.g., Demo, Posts, Projects etc.


  • Other menu items direct to stand alone sections
    • e.g., Courses


  • The menu also has a search function and a day/night mode switch
30 / 177

Academic — Advantages

  • Designed especially for academics in mind
    • features what academics would want to feature
      • e.g., education, publications
31 / 177

Academic — Advantages

  • Designed especially for academics in mind
    • features what academics would want to feature
      • e.g., education, publications


  • Well looked after
    • gets updated very frequently
      • Hugo released v0.71.1 on Monday 25 May 2020, which broke the theme
      • Academic got updated the next day with a fix
    • has a lively community of users and developers behind it
31 / 177

Academic — Advantages

  • Designed especially for academics in mind
    • features what academics would want to feature
      • e.g., education, publications


  • Well looked after
    • gets updated very frequently
      • Hugo released v0.71.1 on Monday 25 May 2020, which broke the theme
      • Academic got updated the next day with a fix
    • has a lively community of users and developers behind it


31 / 177

Academic — Disadvantages

  • Complicated

    • with its high customisation, comes high complexity
    • its widgets can at first be overwhelming
32 / 177

Academic — Disadvantages

  • Complicated

    • with its high customisation, comes high complexity
    • its widgets can at first be overwhelming


  • Popular

    • over 100,000 websites use this theme
    • hard to stand out in this crowd
32 / 177

Academic — Disadvantages

  • Complicated but well documented
    • with its high customisation, comes high complexity
    • its widgets can at first be overwhelming
    • you can handle it on your own


  • Popular but with room for personalisation
    • over 100,000 websites use this theme
    • hard to stand out in this crowd
    • it comes with different colour schemes, fonts
    • there are many potential combinations of widgets
33 / 177

Part 3. Website Backend

34 / 177

Website Backend — Create from within RStudio

  • Create a new R project, specifically for a website

File -> New Project -> New Directory -> Website using blogdown

  • Give your project a name with Directory Name

  • Choose a location for the project with Browse...

    • synced locations, e.g., Dropbox, are likely to cause warning/error messages
      • pause syncing, or add an sync exclusion on Dropbox

35 / 177

Website Backend — Create from within RStudio



  • Click Create Project to start

36 / 177

Website Backend — Directory Structure

Observe 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.

37 / 177

Website Backend — Directory Structure

Observe that the root directory is now populated with files, including

  • /config.yaml and other configuration files under /config/

38 / 177

Website Backend — Directory Structure

Observe that the root directory is now populated with files, including

  • /config.yaml, /config/
  • /content/

    • includes files to be transformed into HTML pages
    • each directory under /content/ is a section of a website
      • e.g., /content/post/ can be viewed at https://janejdoe.netlify.app/post/

39 / 177

Website Backend — Directory Structure — /content/

  • Observe that the files under /content/ are typically Markdown files

    • with the .md extension
40 / 177

Website Backend — Directory Structure — /content/

  • Observe that the files under /content/ are typically Markdown files

    • with the .md extension
  • These files have typically two sections

    • a front matter with the YAML syntax
      • YAML goes between a pair of three hyphens ---

    • and some text
      • using Markdown syntax
40 / 177

Website Backend — Directory Structure

Observe that the root directory is now populated with files, including

  • /config.yaml, /config/
  • /content/
  • /static/

    • contains files that should appear on websites as is
      • e.g., images, PDF files
      • these can be organised within separate directories
        • e.g., images can be put in static/media/
    • Hugo does not transform the files in this folder while generating websites

41 / 177

Website Backend — Directory Structure — Notes

  • Hugo websites follow more or less the same directory structure


  • The structure, as well as other technical details, might change

    • changes come with a new Hugo version
    • a change may or may not break a theme
    • themes are designed, and websites are generated, with a certain version
      • these two versions do not have to be the same, but compatible
42 / 177

Website Backend — Set Hugo Version

Set blogdown.hugo.version in /.Rprofile to the latest Hugo version that you have

  • Hugo version in /.Rprofile is often out of date
  • first check the installed Hugo versions that you have
    • by running blogdown::find_hugo("all") in the Console

  • changes to .Rprofile take affect only after saving the file, and restarting R
    • after saving, follow Session -> Restart R
43 / 177

Website Backend — Serve Site

  • Click the Addins -> Serve Site to preview the site

    • this is equivalent to typing blogdown::serve_site() in the Console
  • Observe that the website is live in the Viewer tab

    • this can be viewed with a browser, by clicking on the window icon

44 / 177

Website Backend — Serve Site

  • Click the Addins -> Serve Site to preview the site

    • this is equivalent to typing blogdown::serve_site() in the Console
  • Observe that the website is live in the Viewer tab

    • this can be viewed with a browser, by clicking on the window icon

45 / 177

Website Project — Serve Site

  • Click the Addins -> Serve Site to preview the site

    • this is equivalent to typing blogdown::serve_site() in the Console
  • Observe that the website is live in the Viewer tab

    • this can be viewed with a browser, by clicking on the window icon
  • You can make live edits in this state

    • e.g., in /config.yaml, change title = "Academic", and save
      • e.g., to title = "YourName"
      • observe the live change in the website

46 / 177

Part 4. Configuration

47 / 177

Configuration — Overview

  • There are four configuration files in the theme

    • /config.yaml
    • /config/_default/languages.yaml
    • /config/_default/menus.yaml
    • /config/_default/params.yaml
48 / 177

Configuration — Overview

  • 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

    • e.g., creating menu items; defining font, language
    • these files are written with the YAML syntax
48 / 177

Configuration — Overview

  • 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

    • e.g., creating menu items; defining font, language
    • these files are written with the YAML syntax


48 / 177

Configuration — YAML Syntax

  • YAML uses key: value pairs

    • keys are pre-defined — mostly by Hugo, but also by each theme
      • e.g., title
    • users supply the values
      • e.g., "Name Surname"
title: "Jane J. Doe"
49 / 177

Configuration — YAML Syntax

  • YAML uses key: value pairs

    • keys are pre-defined — mostly by Hugo, but also by each theme
      • e.g., title
    • users supply the values
      • e.g., "Name Surname"
  • Values can take

    • strings*
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.

50 / 177

Configuration — YAML Syntax

  • YAML uses key: value pairs

    • keys are pre-defined — mostly by Hugo, but also by each theme
      • e.g., title
    • users supply the values
      • e.g., "Name Surname"
  • Values can take

    • strings, in quotation marks
    • numbers, bare
title: "Jane J. Doe"
summaryLength: 30
51 / 177

Configuration — YAML Syntax

  • YAML uses key: value pairs

    • keys are pre-defined — mostly by Hugo, but also by each theme
      • e.g., title
    • users supply the values
      • e.g., "Name Surname"
  • Values can take

    • strings, in quotation marks
    • numbers, bare
    • Boolean values, in lower case, bare
title: "Jane J. Doe"
summaryLength: 30
enableEmoji: true
52 / 177

Configuration — YAML Syntax

  • YAML uses key: value pairs

    • keys are pre-defined — mostly by Hugo, but also by each theme
      • e.g., title
    • users supply the values
      • e.g., "Name Surname"
  • Values can take

    • strings, in quotation marks
    • numbers, bare
    • Boolean values, in lower case, bare
    • sequence of values with a hyphen each
title: "Jane J. Doe"
summaryLength: 30
enableEmoji: true
interests:
- Party politics
- Public policy
- International polities
53 / 177

Configuration — YAML Syntax — Notes

There is an alternative way to write sequence of values

  • in square brackets, separated by comma
title: "Jane J. Doe"
summaryLength: 30
enableEmoji: true
interests: [Party politics, Public policy, International polities]
54 / 177

Configuration — YAML Syntax — Notes

Multiple nesting of keys and sequences is also possible

  • requires indentation with four spaces for the first nesting, and an hyphen for the second
education:
courses:
- course: PhD in Political Science
institution: University of Vienna
year: 2017
- course: MSSc in European Studies
institution: University of Tampere
year: 2009
55 / 177

Configuration — YAML Syntax — Notes

To disable an option in YAML, you can

  • comment its line out with a hash
# title: "Jane J. Doe"
56 / 177

Configuration — YAML Syntax — Notes

To disable an option in YAML, you can

  • comment its line out with a hash
# title: "Jane J. Doe"
  • set it to []
    • this may not work in nests
title: []
56 / 177

Configuration — YAML Syntax — Notes

To disable an option in YAML, you can

  • comment its line out with a hash
# title: "Jane J. Doe"
  • set it to []
    • this may not work in nests
title: []
  • set it to ""
title: ""
56 / 177

Configuration — YAML Syntax — Notes

To disable an option in YAML, you can

  • comment its line out with a hash
# title: "Jane J. Doe"
  • set it to []
    • this may not work in nests
title: []
  • set it to ""
title: ""
  • delete it altogether
    • not recommended, as you might need that key in the future
56 / 177

Exercises — Configuration — /config.yaml

  • Edit one or more values in the /config.yaml file
    • locate the file under the root directory
    • edit at least the title and copyright* keys, with
    • remember to save the file
      • and observe the changes in the RStudio Viewer and/or on a browser


  • Scroll through the other keys
    • to see what else is available that you may wish to edit
    • once your website is online, you should also edit baseurl 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
57 / 177

Exercises — Configuration — params.yaml

  • Edit one or more values in the params.yaml file
    • locate it under /config/_default/
    • edit at least the values for contact details
    • observe the changes in the RStudio Viewer and/or on a browser


15:00
58 / 177

Configuration — menus.yaml

This file configures the website menu

  • creates and orders menu items
  • directs them
    • to a specific section on the homepage
      • e.g., to a widget such as Contact at the bottom of the homepage

    • to a specific page
      • e.g., to a page that lists the titles of all blogposts
      • e.g., to a specific blogpost
59 / 177

Configuration — menus.yaml

  • Define menu items
    • as a list, with the name argument
main
- name: "Posts"
- name: "Courses"
- name: "Twitter"
- name: "CV"
60 / 177

Configuration — menus.yaml

  • Define menu items
  • Order the items
    • with the weight argument


  • Note that
    • the order, not the actual value, matters
      • you could use 1, 4, 9 ... instead

    • using the same value for two or more items should be avoided
main
- name: "Posts"
weight: 10
- name: "Courses"
weight: 30
- name: "Twitter"
weight: 20
- name: "CV"
weight: 40
61 / 177

Configuration — menus.yaml

  • Define menu items
  • Order the items
  • Link them to destinations
    • with the url argument

      • with a number sign # to a widget on the homepage
        • these match a file name under /content/home/

      • with a trailing slash / to sections
        • these match a file or folder name under /content/
      • with URLs to external sites
        • e.g., Twitter

      • with paths relative to the /static/ sub-directory
        • files/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"
62 / 177

Exercises — Configuration — menus.yaml

  • Edit the menus.yaml file, as much as possible now*

    • create, order, and direct menu items
    • observe the changes in the RStudio Viewer and/or on a browser

* You are likely to edit this file throughout the workshop, as your website evolves.

05:00
63 / 177

Configuration — languages.yaml

This file

  • defines the language of the website

    • the default is English
  • can make the site multi-lingual

    • we will not cover it in this workshop
    • instructions available at the above link as well
64 / 177

Configuration — Multi-lingual Sites

  • Considerations

    • who is your target audience?
      • would they be lost if your website was only in one language?
        • if not, perhaps it is not worth the hassle

    • what will be in multiple languages?
      • all website, or some widgets and/or pages?
        • even in a single language setting, widgets and pages can be written in different languages
65 / 177

Configuration — Multi-lingual Sites

  • Considerations

    • who is your target audience?
      • would they be lost if your website was only in one language?
        • if not, perhaps it is not worth the hassle

    • what will be in multiple languages?
      • all website, or some widgets and/or pages?
        • even in a single language setting, widgets and pages can be written in different languages


  • Strategy

    • build your website in full in one language first, than add the second
      • rather then building it multiple languages in tandem
      • hence not covered in the workshop
65 / 177

Exercises — Configuration — languages.yaml


  • Change the langauge of your website, in two steps

    • in languages.yaml:
      • provide a different value to the languageCode key
    • in /config.yaml:
      • edit the value for defaultContentLanguage
03:00
66 / 177

Part 5. Managing Structure

67 / 177

Structure — Overview

  • Structure depends mostly on the way the /content/ directory is organised, including

    • individual pages, such as a homepage
    • sections (collections of pages), such as a blog


  • Each page at the fronted corresponds to a Markdown file at the backend

    • changing the content and/or the position of these files at the backend will change the frontend


  • Sections are organised in separate directories under /content/

    • first-level sub-directories become a section by default
      • e.g. content/post/ is a section (for all blogposts)

    • creating a section under a section requires manual input
      • by adding a file named _index.md under the second-level directory
68 / 177

Structure — Examples

A website with a single page

.
└── /content/
|
└── home.md # <- https://janejdoe.netlify.app/home/
69 / 177

Structure — Examples

A website with two single pages

.
└── /content/
|
├── home.md # <- https://janejdoe.netlify.app/home/
|
└── about.md # <- https://janejdoe.netlify.app/about/
70 / 177

Structure — Examples

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

  • four single pages: home, about, first-post, second-post
  • one section page: blog
    • because it is a first order sub-directory
    • by default, this section page is tiled Blog, showing the links to the two posts
71 / 177

Structure — Examples

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 name
  • there are three single pages: home, about, blog
  • blog is not a section page, but a simple page, showing a blogpost
72 / 177

Structure — Examples

A 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/
73 / 177

Structure — Examples

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/
74 / 177

Structure — Examples

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/
75 / 177

Structure — Examples

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 sections
76 / 177

Structure — Examples

Having _index.md in first-order sub-directories is optional, but may be helpful

  • can add metadata and/or text to section pages
    • e.g., these are by default titled as the plural of section names
      • e.g., the page publication/ is titled as Publications
    • change this behaviour with _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/
77 / 177

Exercises — Structure

  • Explore the directory structure of your website in RStudio

    • how many pages and sections are there?
    • are there any subsections?
      • hint: see courses/


  • Do a matching exercise

    • open the example site on a browser
    • try and find the front end of the following file
      • /content/publication/journal-article/index.md

    • compare the back end with front end
05:00
78 / 177

Structure — home/ — Overview

  • The homepage in Academic does not exactly follow the structure above

    • every file under home/ is not a stand alone page
    • these files, called widgets, are rather stitched under one another
      • considered as one of the strengths of the theme
      • some academics prefer to have only this page
79 / 177

Structure — home/ — Overview

  • The homepage in Academic does not exactly follow the structure above

    • every file under home/ is not a stand alone page
    • these files, called widgets, are rather stitched under one another
      • considered as one of the strengths of the theme
      • some academics prefer to have only this page


  • Widgets are complicated Markdown files

    • can be stitched under one another
    • can get text from files elsewhere
      • e.g., the contact.md widget gets the address information from params.yaml
79 / 177

Structure — home/ — Overview

  • The homepage in Academic does not exactly follow the structure above

    • every file under home/ is not a stand alone page
    • these files, called widgets, are rather stitched under one another
      • considered as one of the strengths of the theme
      • some academics prefer to have only this page


  • Widgets are complicated Markdown files

    • can be stitched under one another
    • can get text from files elsewhere
      • e.g., the contact.md widget gets the address information from params.yaml


  • A homepage can have one, more, or all widgets

    • widgets can be deactivated or repeated
    • they can be re-ordered as well
79 / 177

Structure — home/ — Widgets

80 / 177

Structure — home/ — Widgets


  • Widgets are in fact Markdown files, with .md extension

    • each has YAML syntax as the front matter
    • some has Markdown text as well
      • e.g., demo.md
    • because they can have both variables and text, YAML goes between a pair of three hashes
80 / 177

Structure — home/ — Widgets


  • Widgets are in fact Markdown files, with .md extension

    • each has YAML syntax as the front matter
    • some has Markdown text as well
      • e.g., demo.md
    • because they can have both variables and text, YAML goes between a pair of three hashes


  • Widgets are located under /content/home/

    • except index.md, each file is a widget — some duplicates of the same type
80 / 177

Structure — Homapage — Widgets — Important Keys

widget: "pages"
81 / 177

Structure — Homapage — Widgets — Important Keys

  • Some keys are common across all widgets

    • Indicate the type of the widget
    • De-activate a widget
widget: "pages"
active: false
82 / 177

Structure — Homapage — Widgets — Important Keys

  • Some keys are common across all widgets

    • Indicate the type of the widget
    • De-activate a widget
    • Order a widget in relation to other widgets
widget: "pages"
active: false
weight: 9
83 / 177

Structure — Homapage — Widgets — Important Keys

  • Some keys are common across all widgets

    • Indicate the type of the widget
    • De-activate a widget
    • Order a widget in relation to other widgets
    • Title and/or subtitle it
widget: "pages"
active: false
weight: 9
title: "Recent Publications"
subtitle: ""
84 / 177

Structure — Homapage — Widgets — Important Keys

  • Some keys are common across all widgets

    • Indicate the type of the widget
    • De-activate it
    • Order it in relation to other widgets
    • Title and/or subsitle it
  • Some keys are widget specific

    • Link it to a content section
widget: "pages"
active: false
weight: 9
title: "Recent Publications"
subtitle: ""
page_type: "publication"
85 / 177

Structure — Homapage — Widgets — Important Keys

  • Some keys are common across all widgets

    • Indicate the type of the widget
    • De-activate it
    • Order it in relation to other widgets
    • Title and/or subsitle it
  • Some keys are widget specific

    • Link it to a content section
  • 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"
86 / 177

Structure — Adding

  • There are at least three ways to add new pages and sections

    • create new files and directories, respecting the directory structure of Hugo and Academic
    • rename and edit the existing files and folders for your purposes
    • duplicate, rename, and edit the existing files and folders that are in use


  • RStudio has helpful buttons for these purposes
    • to create, duplicate, and/or rename
    • alternatively, use your operating system
87 / 177

Exercises — Structure — Adding

Rename one or more blogposts and publications on your website

  • observe the changes in RStudio Viewer


Hint:

10:00
88 / 177

Structure — Removing

There are at least two ways to remove pages and sections

  • delete them, respecting the directory structure of Hugo and Academic
    • perhaps, you are sure there will not be two authors on your website
      • the example site comes with two author profiles, under /content/authors/
      • with usernames admin (main) and 吳恩達 (secondary)
      • it is safe to delete the latter

  • turn them into drafts, by setting
    • active: false in the YAML of widgets
    • draft: true in the YAML of other Markdown files
    • perhaps, you think you may need a section in the future
89 / 177

Exercises — Structure — Removing — Widgets

  • Keep only the widgets that you would like to have on your website

    • set active: false in the front matter of the undesired widget
    • re-order the desired widgets if necessary
    • check if the homepage looks and works as expected


  • Hint:

    • /content/home/index.md is not a widget
      • although it is under the same directory with all widgets

    • on JJD's website, the following widgets are active
      • hero, about, experience, publications, posts, contact

    • you may need to configure the menu in parallel
      • by editing /config/_default/menus.yaml
10:00
90 / 177

Structure — Removing — Non-Widget Markdown

  • You can deactivate a specific page in a section

    • add draft: true to file of that page
    • e.g., /content/publication/journal-article/index.md


  • You can deactivate whole sections in one go

    • add draft: true to file of that section
    • e.g., /content/publication/_index.md


  • You can deactivate whole sections except one or more pages

    • add draft: true to file of that section
    • e.g., /content/publication/_index.md

    • add draft: false to the file of a page
    • e.g., /content/publication/journal-article/index.md
91 / 177

Structure — Removing — Non-Widget Markdown

  • Not all sections have _index.md to start with

    • e.g., /content/project/
    • you can add one, following

File -> New File -> R Script


  • Draft pages and sections are still visible to you in live preview

    • e.i., when you use blogdown::serve_site
    • but not to the visitors of your website
      • e.i., if you publish your site
92 / 177

Exercises — Structure — Non-Widget Markdown

  • Keep only the sections and pages that you would like to have on your website

    • set the draft key to true or false in the front matter of relevant files
    • check if the website looks and works as expected


  • Hint:

    • on JJD's website, the following sections are active
      • home, authors, post, publication
      • admin is the only author

    • you may need to configure the menu in parallel
      • by editing /config/_default/menus.yaml
10:00
93 / 177

Part 6. Deployment

94 / 177

Deployment — Overview

  • Deployment of your website onto a web server makes it visible online

    • your website is currently available on your computer only


  • You can deploy your website at any web server that you prefer

    • Netlify is a popular choice as a web server
      • easy to set up
      • includes a free plan
      • recommended by the authors of the blogdown package and the Academic theme
95 / 177

Deployment — Workflow

Deployment occurs in two steps

  • we push the website files, from our computer, into a GitHub repository

    • for the first time, and after one or more edits
    • with commands or clicks in RStudio


  • Netlify does the rest automatically, in a minute or so

    • (re-)retrieves the files
    • generates the website with Hugo
    • (re-)publishes the website
96 / 177

Deployment — Git and GitHub — Definitions

  • Git
    • a software that keeps track of versions of a set of files
    • it is local, the records are kept on your computer
97 / 177

Deployment — Git and GitHub — Definitions

  • Git
    • a software that keeps track of versions of a set of files
    • it is local, the records are kept on your computer
  • GitHub
    • a hosting service, or a website, that can keep the records
    • it is like Dropbox, but specifically structured to keep records with Git
97 / 177

Deployment — Git and GitHub — Definitions

  • Git
    • a software that keeps track of versions of a set of files
    • it is local, the records are kept on your computer
  • GitHub
    • a hosting service, or a website, that can keep the records
    • it is like Dropbox, but specifically structured to keep records with Git
  • Repository, or repo
    • a set of files whose records are kept together, by Git and/or on GitHub
    • it is like a folder, which can keep files and other folders containing files
97 / 177

Deployment — Git and GitHub — Definitions

  • To commit
    • to take a snapshot of, to version a repository
    • it is like saving a new version of all changed files in your folder with a new name
    • it is local, the records are kept on your computer unless you push
98 / 177

Deployment — Git and GitHub — Definitions

  • To commit
    • to take a snapshot of, to version a repository
    • it is like saving a new version of all changed files in your folder with a new name
    • it is local, the records are kept on your computer unless you push
  • To push
    • to move the records from Git to GitHub, from your computer to online
    • it is like uploading (the new versions of) your files to a website,
    • it also involves merging, if this not the first push
98 / 177

Deployment — Git and GitHub — Definitions

  • To commit
    • to take a snapshot of, to version a repository
    • it is like saving a new version of all changed files in your folder with a new name
    • it is local, the records are kept on your computer unless you push
  • To push
    • to move the records from Git to GitHub, from your computer to online
    • it is like uploading (the new versions of) your files to a website,
    • it also involves merging, if this not the first push
  • To pull
    • to move the updated records from GitHub to your computer
    • it is like downloading a zipped folder of files, and merging with the ones on your computer
98 / 177

Deployment — Git and GitHub — Workflow

Working with with Git and GitHub requires

  • initial setup, done once*
    • unless for a new computer or, if ever, a new GitHub account
    • a bit technical, but worth the hassle


  • project setup, repeated for every RStudio project
    • shorter, less complicated

[*] We have started this process already, in Part 1 of the workshop, by downloading and installing Git and signing up for GitHub.

99 / 177

Deployment — Git and Github — Inital Setup

1) Enable version control with RStudio

  • from the RStudio menu, follow:

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

100 / 177

Deployment — Git and Github — Inital Setup

2) Set Git Bash as your shell (Windows-only step)

  • from the RStudio menu, follow:

Tools -> Global Options -> Terminal -> New terminals open with: Git Bash

101 / 177

Deployment — Git and Github — Inital Setup

3) Introduce yourself to Git

  • from the RStudio menu, follow:

Tools -> Terminal -> New Terminal


  • enter the following lines in the Terminal
    • replacing the relevant parts with your personal information
      • e.g., the email address that you have used to sign up for GitHub
git config --global user.name "YOUR NAME"
git config --global user.email "YOUR EMAIL ADDRESS"


  • enter the following line in the Terminal
    • to observe whether the previous step was successful
git config --global --list
102 / 177

Deployment — Git and Github — Project Setup

1) Initiate local version control with Git

  • from the RStudio menu, follow:

Tools -> Version Control -> Project Setup... -> Version Control System -> Git


  • after confirming your new repository, and restarting the session, observe that

    • now there is now a Git tab in RStudio,
      • documenting the differences between you local repository and the one on GitHub
      • when you change a file, it will appear here

    • your project now includes a .gitignore file
      • this is where you can list files and/or folders to be excluded from being tracked
103 / 177

Deployment — Git and Github — Project Setup

2) Create a new GitHub repository

  • on GitHub, follow:

Repositories -> New -> Repository name (e.g., "my_website") -> Public -> Create repository


104 / 177

Version Control — Git and Github — Project Setup

3) Push an existing repository

  • from the RStudio menu, follow:

Tools -> Terminal -> New Terminal

  • enter the following lines in the Terminal
    • with .yellow-h[your] username and repository name
git remote add origin https://github.com/USER_NAME/REPOSITORY_NAME.git
git add .
git commit -m "initial commit"
git push -u origin master


  • Notice that
    • your files are now online at your GitHub repository
    • we have completed the first step in deployment
105 / 177

Deployment — Netlify — Setup

1) After logging in to Netlify, follow

New site from Git -> GitHub


  • complete the authorisation process
    • so that GitHub allows Netlify to access your repository
    • once completed, pick your repository from the list, and click Deploy site
      • the default settings should work
106 / 177

Deployment — Netlify — Setup

2) While on the Site overview page, click on Domain settings

  • change the name of your site to something more meaningful
    • by default, Netlify assigns a random name
      • e.g., hus324n.netlify.app

  • if you have a custom domain name
    • e.g., you have purchased yournamesurname.com
    • click on Add custom domain and follow the instructions

  • if you don't have a custom domain name,
    • click on Options to change the random address to something more meaningful
      • e.g., yournamesurname.netlify.app
107 / 177

Deployment — Workflow — In Practice

1) In RStudio, edit your site with the its URL

  • this is done through the baseurl key in /config.yaml
  • set it to https://yournamesurname.netlify.app/
    • including the trailing slash
  • observe whether the site still builds, in Viewer


2) Commit and Push

  • under the Git tab in RStudio, find the file
    • it will have M, for modified, as Status

  • tick Staged* for that file, and click Commit
    • enter a Commit message that summarises the edit
    • click Commit to create a record of the new version locally to your computer
    • click Close -> 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.

108 / 177

Deployment — Notes

  • Avoid pushing your project to GitHub without checking it works locally first
    • use blogdown for your advantage, observe it in Viewer
109 / 177

Deployment — Notes

  • Avoid pushing your project to GitHub without checking it works locally first
    • use blogdown for your advantage, observe it in Viewer


  • If things still go wrong, you can revert back to the version on GitHub
    • git checkout HEAD PATH/TO/FOLDER/OR/FILE reverts a specific folder or file
    • git reset --hard reverts all
109 / 177

Deployment — Notes

  • Avoid pushing your project to GitHub without checking it works locally first
    • use blogdown for your advantage, observe it in Viewer


  • If things still go wrong, you can revert back to the version on GitHub
    • git checkout HEAD PATH/TO/FOLDER/OR/FILE reverts a specific folder or file
    • git reset --hard reverts all


109 / 177

Exercises — Deployment

  • Practice deployment one more time

    • edit a piece of text that is visible on your website, and save
      • e.g., the title key in /config.yaml

    • observe the change locally, in Viewer
    • stage, commit, push
    • observe the change online, in a browser
03:00
110 / 177

Part 7. Adding Content

111 / 177

Content — Overview

Most of what is visible at website frontend is stored in three directories at the backend

  • some files are under the /assets/ directory
    • most importantly, the website icon


  • other display-as-is materials are under the /static/ directory
    • e.g., PDFs, images


  • most materials are under the /content/ directory
    • e.g., Markdown files matching pages, widgets for the homapage
112 / 177

Content — /assets/

  • This directory stores non-textual files to be processed
    • by Hugo to generate the website
    • e.g., images


  • By default, files under /assets/ do not have a matching URL
    • visitors will not be able to view them unprocessed on a browser


  • Adding a file to /assets/ is straightforward
    • move or copy into it as normal


  • Academic looks in /assets/media/ for a website icon
    • it appears, e.g., on web browser tabs
    • it must be named icon.png
    • if not, Academic uses the default icon
113 / 177

Exercises — Content — /assets/

Change your website icon

  • by placing an image named icon.png to /assets/media/
  • stage, commit, push
  • observe the change online, in a browser


Hint:

  • website icons are not visible in RStudio Viewer
  • images are best saved as a square 512x512 pixel
  • JJD's icon is the same as her profile picture
03:00
114 / 177

Content — /static/

  • This directory stores non-textual files not to be processed
    • Hugo simply copies these files over to frontend
    • e.g., images
115 / 177

Content — /static/

  • This directory stores non-textual files not to be processed
    • Hugo simply copies these files over to frontend
    • e.g., images


  • By default, files under /static/ have a matching URL
    • visitors will be able to view them unprocessed on a browser
.
└── /static/
|
└── pfofile-photo.jpg # <- https://janejdoe.netlify.app/pfofile-photo.jpg
|
└── files/
|
└── cv.pdf # <- https://janejdoe.netlify.app/files/cv.pdf
115 / 177

Content — /static/

  • This directory stores non-textual files not to be processed
    • Hugo simply copies these files over to frontend
    • e.g., images


  • By default, files under /static/ have a matching URL
    • visitors will be able to view them unprocessed on a browser


  • Adding a file to /static/ is straightforward
    • move or copy into it as normal


  • /static/ is the right directory to store PDFs
    • e.g., cv, publications
116 / 177

Exercises — Content — /static/

Make one or more files available as-is on your website

  • by placing them under /static/
    • directly, or under a sub-directory
  • stage, commit, push
  • observe the change online, in a browser


Hint:

  • static files are not visible in RStudio Viewer
  • JJD's website has her cv and two publications available to view as-is
    • download them from her website
05:00
117 / 177

Content — /content/

  • This directory stores mostly textual files to be processed

    • mostly by Hugo, some by blogdown
    • e.g., Markdown files


  • Most files under this directory are plain Markdown files

    • with the .md extension
    • transformed by BlackfridayHugo's Markdown rendering engine, so is Netlify's — into HTML
      • no need for blogdown, but cannot execute any code


  • Some are R Markdown files

    • with either .Rmd or .Rmarkdown extension
      • transformed by pandocblogdown's rendering engine
        • therefore can execute code, thanks to blogdown
      • we will cover these in Part 8
118 / 177

Content — Markdown Syntax — Overview

  • Markdown is a plain-text file

    • with its own syntax
      • much easier to write than HTML
      • the differences between plain and R Markdown syntaxes are minimal
    • versatile, can be transformed into many different formats, including HTML
119 / 177

Content — Markdown Syntax — Overview

  • Markdown is a plain-text file

    • with its own syntax
      • much easier to write than HTML
      • the differences between plain and R Markdown syntaxes are minimal
    • versatile, can be transformed into many different formats, including HTML



  • R Markdown (.Rmd and .Rmarkdown) follows the syntax in Pandoc's Markdown

    • for the complete rules of the syntax, see Pandoc User's Guide
    • for a useful summary of the syntax, see the R Markdown Cheat Sheet
119 / 177

Content — Markdown Syntax — Strategies

  • 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

      • maximises the functionality from each
      • requires learning the small differences if necessary
    • use .Rmd for all pages

      • requires learning only one syntax
      • misses the additional functionality in .md
      • folders get cluttered with intermediate files
120 / 177

Content — Markdown Syntax — Strategies

  • 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

      • maximises the functionality from each
      • requires learning the small differences if necessary
    • use .Rmd for all pages

      • requires learning only one syntax
      • misses the additional functionality in .md
      • folders get cluttered with intermediate files


  • The syntax in the following slides of this section will work with both types

120 / 177

Content — Markdown Syntax — Lines

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.

121 / 177

Content — Markdown Syntax — Hard Brakes

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.

122 / 177

Content — Markdown Syntax — Block Quotes

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

123 / 177

Content — Markdown Syntax — Paragraphs

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.

124 / 177

Content — Markdown Syntax — Comments

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.

125 / 177

Content — Markdown Syntax — Headers

The number sign # introduces headers; lower levels are created with additional signs — up to total five levels

# Introduction becomes

Introduction

## 1. Introduction becomes

1. Introduction

### 3.1 Introduction becomes

3.1 Introduction

#### Introduction becomes

Introduction

##### Introduction becomes

Introduction
126 / 177

Content — Markdown Syntax — Emphases

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

127 / 177

Content — Markdown Syntax — Strikethrough

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

128 / 177

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.

129 / 177

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

130 / 177

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

130 / 177

Content — Markdown Syntax — Footnotes

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.

131 / 177

Content — Markdown Syntax — Lists

Lines starting with asterisk * as well as plus + or minus signs introduce lists

- books
- articles
- reports
  • books
  • articles
  • reports
132 / 177

Content — Markdown Syntax — Lists — Nesting

Lists can be nested within each other, with indentation

+ books
+ articles
- published
- under review
+ revised and resubmitted
- work in progress
  • books
  • articles
    • published
    • under review
      • revised and resubmitted
    • work in progress
133 / 177

Content — Markdown Syntax — Lists — Numbering

List items can be numbered

1. books
2. articles
- published
- under review
+ revised and resubmitted
- work in progress
  1. books
  2. articles
    • published
    • under review
      • revised and resubmitted
    • work in progress
134 / 177

Content — Markdown Syntax — Lists — Numbering

List items can be numbered

1. books
2. articles
- published
- under review
+ revised and resubmitted
- work in progress
  1. books
  2. articles
    • published
    • under review
      • revised and resubmitted
    • work in progress
135 / 177

Content — Markdown Syntax — Lists — Tasks Lists

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
136 / 177

Content — Markdown Syntax — Dashes

Two hyphens grouped together introduce an en-dash

‐‐ becomes


Three hyphens grouped together introduce an em-dash

‐‐‐ becomes

137 / 177

Content — Markdown Syntax — Highlithing

Highlight any piece of text, by putting it in between a pair of backticks `

`code` becomes code

138 / 177

Content — Markdown Syntax — Highlithing

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)
138 / 177

Content — Markdown Syntax — Tables

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
139 / 177

Content — Markdown Syntax — Tables

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

  • R Markdown makes it possible to customise hand-made tables futher
    • we will cover these in Part 8
139 / 177

Content — Markdown Syntax — Images

The syntax ![](figurename.extension) embeds images into HTML outputs

  • similar to the link syntax, only this time it is preceded by an exclamation mark !
  • goes a new line, separate from the text
  • assumes the figure is in the same folder with the Markdown file*

[*] If the image is in static/, use a path relative to that directory, e.g., ![](/media/figure.extension)

140 / 177

Content — Images — Markdown Syntax

![](/media/boards.jpg)

141 / 177

Content — Images — Notes

  • Images can also be added through YAML
    • e.g., to blogposts, publications
    • using the image key


  • These images must be saved in the same directory
    • as featured.jpg
    • rename or remove it if having them is not desireble
      • removing the image key in YAML is not effective
142 / 177

Exercises — Content

  • Edit one or more Markdown files in your website project

    • observe the change locally, in Viewer
    • stage, commit, push
    • observe the change online, in a browser


  • 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 post
    • by copy the text from the website to save time

      • paste into Markdown, and add the syntax
30:00
143 / 177

Part 8. R Markdown

144 / 177

R Markdown — Overview

  • R Markdown is a special type of Markdown
    • can run code, and embed the results from data into HTML
    • have the .Rmd or .Rmarkdown extension
145 / 177

R Markdown — Overview

  • R Markdown is a special type of Markdown
    • can run code, and embed the results from data into HTML
    • have the .Rmd or .Rmarkdown extension


  • Hugo cannot transform R Markdown into HTML
    • that is why we need the blogdown package
    • transformation of these files takes places locally on your computer
    • not remotely at the server — e.g., Netlify
145 / 177

R Markdown — Overview

  • R Markdown is a special type of Markdown
    • can run code, and embed the results from data into HTML
    • have the .Rmd or .Rmarkdown extension


  • Hugo cannot transform R Markdown into HTML
    • that is why we need the blogdown package
    • transformation of these files takes places locally on your computer
    • not remotely at the server — e.g., Netlify


  • R Markdown is very similar to Markdown in terms of syntax
    • except that it includes code
      • mostly R code, but could also be python
145 / 177

R Markdown — Code — Overview

Most codes go inside code chunks

  • e.g., code that imports and cleans data, and/or produces tables and/or figures
```{r}
df <- mtcars %>%
mutate(disp_litre = disp / 61.0237)
```

Codes can also go in line with text

  • .e.g., code that result in a single statistic
The average engine displacement of the cars in the dataset is `r mean(df$disp_litre)` litres.
146 / 177

R Markdown — Code Chunks — Overview

  • Code chunks are delimited spaces between a pair of three backticks
    • below is an empty chunk for R code
```{r}
```
147 / 177

R Markdown — Code Chunks — Overview

  • Code chunks are delimited spaces between a pair of three backticks
    • below is an empty chunk for R code
```{r}
```
  • r is an option of the chunk, indicating that the code in the chunk above should be run by R
    • it could have been python, which we will not cover in this workshop
    • options go in a pair of curly brackets, on the same line with the first delimiter
147 / 177

R Markdown — Code Chunks — Overview

  • Code chunks are delimited spaces between a pair of three backticks
    • below is an empty chunk for R code
```{r}
```
  • r is an option of the chunk, indicating that the code in the chunk above should be run by R
    • it could have been python, which we will not cover in this workshop
    • options go in a pair of curly brackets, on the same line with the first delimiter
  • Chunks can be placed anywhere in .Rmd documents
    • their output will be placed instead of, or following,* the code chunk on the website page

[*] Depending on whether code chunks are displayed or not. See the echo option in the following slides.

147 / 177

R Markdown — Code Chunks — Labels

Label the code chunks right after r

```{r, tidydata}
df <- mtcars %>%
mutate(disp_litre = disp / 61.0237)
```
148 / 177

R Markdown — Code Chunks — Labels

Label the code chunks right after r

```{r, tidydata}
df <- mtcars %>%
mutate(disp_litre = disp / 61.0237)
```


Note that

  • labels are optional, but recommended because they
    • can be used in text, to refer to tables or figures that code chunks produce
    • can help with navigating through error messages

  • duplicate labels lead to an error
148 / 177

R Markdown — Code Chunks — Options

  • Code chunks take options, listed on the same line with the first delimiter, in curly brackets

    • avoid spaces around the equal sign = between option tags and values
      • such spaces might lead to errors

    • in the example below, the chunk is labelled as setup, and and the include option is set to FALSE
      • with this option and value, nothing from this chunk will be included in the output document
```{r, tidydata, include=FALSE}
```


149 / 177

R Markdown — Code Chunks — Options — Defaults

Options have default values

  • e.g., for echo, the default is TRUE
    • echo: should the source code printed in the output? — yes

  • therefore the following two chunks have the same function
```{r, tidydata}
```
```{r, tidydata, echo=TRUE}
```
150 / 177

R Markdown — Code Chunks — Options — Defaults

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
151 / 177

R Markdown — Code Chunks — Options

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
152 / 177

R Markdown — Code Chunks — Other Useful Options

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)

153 / 177

R Markdown — Code Chunks — Other Useful Options

Cache results for future compilations

```{r ... cache=TRUE}
```
154 / 177

R Markdown — Code Chunks — Other Useful Options

Cache results for future compilations

```{r ... cache=TRUE}
```

Prevent R from running the code in the chunk altogether

```{r ... eval=FALSE}
```
154 / 177

R Markdown — Code Chunks — Other Useful Options

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}
```
154 / 177

R Markdown — Code Chunks — Other Useful Options

Define the actual dimensions of figures, in inches

```{r ... fig.height=6, fig.width=9}
```
155 / 177

R Markdown — Code Chunks — Other Useful Options

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%"}
```
155 / 177

R Markdown — Code Chunks — Other Useful Options

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"}
```
155 / 177

R Markdown — Code Chunks — Other Useful Options

Define captions for figures

```{r ... fig.caption="A Scatter Plot"}
```
156 / 177

R Markdown — Code Chunks — Other Useful Options

Define captions for figures

```{r ... fig.caption="A Scatter Plot"}
```

Set the resolution for figures

```{r ... dpi=300}
```
156 / 177

R Markdown — Code Chunks — Other Useful Options

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;"'}
```
156 / 177

R Markdown — Code Chunks — The Setup Chunk

It is recommended to use the first code chunk for general setup, where you can

  • define your own defaults for chunk options, with knitr::opts_chunk$set()
    • avoids repeating chunk options

  • load the necessary packages

  • import raw data
```{r, setup, include=FALSE}
# chunk option defaults
knitr::opts_chunk$set(echo=FALSE, message=FALSE)
# packages
library(dplyr)
library(ggplot2)
library(knitr)
# data
df_raw <- mtcars
```
157 / 177

R Markdown — Code Chunks — The Setup Chunk — Data

Note that the data source can be anywhere that R can access

```{r, setup, include=FALSE}
...
# this dataset is available online
df_online <- read.csv("http://www.parlgov.org/static/data/development-cp1252/view_party.csv")
# this dataset is in the same directory as my .Rmd file
df_local <- read.csv("view_cabinet.csv")
```
158 / 177

R Markdown — Code Chunks — The Data Chunk

I recommend using the second chunk for the main operations* on raw data

  • e.g., for data cleaning and other transformations
  • some minor transformations could be left to lower chunks
    • e.g., capitalizing variable names for figures
```{r, data, echo=FALSE ...}
df <- df_raw %>%
mutate(disp_litre = disp / 61.0237)
```
159 / 177

R Markdown — Inline Code — Overview

Code can also be incorporated in text, with the `r ` syntax

  • unlike chunks, these do not take options

  • the output document will display the result of the code
    • in the exact place of the source code

  • the result of the code will have the same formatting with the text
160 / 177

R Markdown — Inline Code — Examples

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.

161 / 177

R Markdown — Figures

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.

162 / 177

R Markdown — Figures — Cross-References

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()
```

See Figure 1 below.

      Figure 1. A scatterplot of cars.

163 / 177

R Markdown — Tables —

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.

164 / 177

R Markdown — Tables — Cross-References

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.

165 / 177

R Markdown — Tables — Hand-Made

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.

166 / 177

R Markdown — Tables — Hand-Made

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
167 / 177

R Markdown — Tables — Hand-Made

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
Table 1: A hand-made table with R Markdown

    Centered            Right-Aligned
First cell First cell
Second cell Second cell
Third cell Third cell
168 / 177

R Markdown — Tables — Hand-Made

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
Table 1: A hand-made table with R Markdown

    Centered            Right-Aligned
First cell First cell
Second cell Second cell
Third cell Third cell
169 / 177

R Markdown — Tables — Hand-Made

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
Table 1: A hand-made table with R Markdown

    Centered            Right-Aligned
First cell First cell
Second cell Second cell
Third cell Third cell
170 / 177

R Markdown — Tables — Hand-Made

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


Table 1: 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
171 / 177

R Markdown — Tables — Hand-Made

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


Table 1: 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.

172 / 177

R Markdown — Tables — Hand-Made — Cross-References

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


Table 1: A hand-made table with R Markdown
173 / 177

Exercises — R Markdown

  • Add and/or edit one or more R Markdown files in your website project

    • observe the change locally, in Viewer
    • stage, commit, push
    • observe the change online, in a browser


  • Hint, if you are re-creating JJD's website:

    • add and edit the following file

    • by copy the text from the website to save time

      • paste into R Markdown, and add the code and syntax
30:00
174 / 177

References

175 / 177

References

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.

176 / 177

The workshop ends here.

Congratulations for making it this far, and

thank you for joining me!

177 / 177

Who am I?

Resul Umit

  • post-doctoral researcher at the University of Oslo

  • teaching and studying representation, elections, and parliaments

    • a recent publication: Parliamentary communication allowances do not increase electoral turnout or incumbents’ vote share
2 / 177
Paused

Help

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