Blogdown R



  1. Blogdown Rmd
  2. Blogdown Book
  3. Blogdown Rstudio Connect

Abstract

The SciViews web site is completely refactored.

This page shows how posts are presented with the new skin.

I’m a geographer whose work focuses on GIS and spatial analysis. I work primarily in R and Python using open source tools. This blog serves primarily to share new tools, tips and techniques I’ve. My Wordpress website was a painfully heavy, bloathed website. No need for all the gadgets and features, which I don't use anyway.

Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents (among other possible formats). For more details on using R Markdown see http://rmarkdown.rstudio.com. This version supports YAML header starting and ending with three dashes (---). It also includes improvements for scientific documents (figures and tables numbering and reference, equations and equations numbering, citations and bibliographic references, …)

Here are the various R Markdown features you can use:

Headers

  • Header with 6 levels, either with #, or with underline:

Some text…

Header 2

Some text…

Header 3

Some text…

Header 4

Some text…

Header 5

Some text…

Header 6

Some text…

An alternate syntax for headers:

Headers can contain formatting and links

simple link, simple code and code inside link.

Take care that a blank line is required before headers as#22 this could too easily be interpretted as a header otherwise.

  • One can put identifiers after header, to allow linking to them elsewhere. Otherwise, headers are autoidentified by a special kind of reformatting of the string. Note also that references to headers can also be implicit. That is, [linking to a header], or [linking to a header][] should work too: this is a link to the abstract.

An identified header

  • One can force unnumbered titles using {-} or {.unnumbered} (providing, of course, that the other headers are numbered).

Basic text formatting

  • Bold using bold or bold

  • Italic using italic or italic, but intra_word_underscore is not interpreted (use stars for that like in this word)

  • Superscript, or subscript. No space can occur inside super- or subscript. If you need it, backslash-escape the space like Pa cat.

  • Strikethrough with this formatting.

  • Formattings can be combined of course, like bold italic with superscript.

  • Inline code like x <- 1, and if you need backquote inside it `@var` <- 2.

  • Links are automatically detected like http://example.com, or can be explicitly indicated (with a different text) like some example. Note that Markdown uses also reference links. You can also put your links between angle brackets http://example.com.

  • You can use any UTF-8 character (at least for HTML documents (examples: µm, Ω, Æ, ∫√)…

  • You need to backshlash-escape punctuation you don’t want to be interpreted ad formatting code, like *foo*.

  • A nonbreaking space is simply an escaped space, like between “Fig.” and “3” here: Fig. 3.

  • A few sequences of characters produce special characters. Use of –dashes– and —em-dashes—. Three dots is ellipsis… and I can use any unicode, too, for special characters, like 😌.

Special paragraphs and other items

  • Quoted text (need blank line before it to avoid misinterpretation of> inside a paragraph)

Some quoted text

With two paragraph…

More quoted
with a second paragraph within the same quote block.

And double quotation

with two paragraphs…

  • Line blocks
This is line block
It respect text position
Like here and you can go to the line
And a new line here
  • Preformatted text:

    Some preformatted textusing indentation

  • Preformatted or verbatim sections indented with four spaces of fenced (but only fenced blocks work in lists and are thus the preferred mean to do so). Fenced blocks are delimited by three or more tildes (~) or backticks (`) and they must be separated from the surrounding using blank lines. You can use identifiers too like in this block:

It is very easy to indicate a language, and syntax highlighting will be used for it:

It can also be specified in a more complex way, and with marks allowing to link to it:

Then you can link to it like here.

  • Horizontal rule or page break using four or more *, - or _ optionally separated by spaces
  • Line breaks when ending with two or more spaces
    like this paragraph. However, this is not very visible, nor usable in table. So you can also use a backslash followed by a newline
    and this approach is the only way to do it in tables!

  • You can escape special characters except in code block or inline code if you don’t want them to be interpreted as formatting marks like _here_.

  • Non-breaking space is entered as a backslash-escaped space ().

  • Comment that do not appear in the final document are similar to HTML comments (<!-- comment-->), but can also be entered using the [//]: syntax.

  • Smart punctuation is used and converts straight quotes into curly ones like ‘here’ or “here”. It will also interpret -- as en-dash –, --- as em-dash —, and ... as ellipses … Moreover, nonbreaking spaces are automatically used after certain items like Mr. Schmidt.

  • Note that raw HTML (with or without interpretation of markdown inside it) can be included too.

  • Footnotes1 are easy to insert. Another example2. And here, I use an inline footnote3.

Text after the long note…

Lists

  • Unordered list (using *, + or -)

    • Second level
  • Compact

  • list

  • of items

  • Loose

  • list

  • of items

  1. Ordered list

    1. Second level
    2. Second level, second item
  2. Back to first level

  3. There is a mechanism to include paragraphs inside the list using indentation (don’t forget the empty line in between to start a new paragraph):

  4. Fourth item

  • The fancy list extension allow for using #. for ordered lists, as well as something like 1), or (I) for instance:
  1. First item
  2. Second item
  1. First item
  2. Second item
  3. Third item
  4. Fourth item
  • Definition lists are also supported (definitions must start with : or ~) and blank lines are optional between the term and its definition (loose vs compact form), but not before the term. Finally, several defintions are allowed for the same term.
Term 1

Definition 1

Term 2 with inline markup

Definition 2

Third paragraph of definition 2.

or

Term 1
Definition 1
Term 2
Definition 2a
Definition 2b
  • Numbered example lists use a sequential numbering throughout the whole document and use the @. syntax:
  1. First item
  2. Second item

Some text

  1. Third item

You can give them labels (alphanumeric + character + hyphen) and refer to them later on. You can also enclose it into parentheses, but it does not change how it is displayed:

  1. This is a good example

As example 4 illustrates4, …

And what if I refer to it before the label like 5? Yes! It works! But unfortunately, there is no link to example 5.

  1. A bad example

Finally, to force ending a list, just add a comment where you want to end it (same trick applies for restarting another numbered list):

  1. list item

  2. another item

    Formatted block with spaces does not work inside lists

  3. third list item

  1. New list item #1

Indent paragraphs or blocks or chunks (see hereunder) following a list item to include it in the list:

  1. The area of a circle with a given radius is:

  2. As you can see, the R chunk and its associated results are included in the list element!

Images

  • To insert images in your document, you use:

The official R logo.

An inline image: . Note here that when an image appears alone in its line, it is interpreted as a figure (possibly with caption), and otherwise, it is interpeted as an inline image.

Reference links

  • Reference links are done this way a linked part, or for images:

Hugo shortcodes

  • Tweeter. In R Markdown, you should not use the {{< tweet 936232450006704128 >}} syntax. Instead, you should use:

Excited about the new R Release? #rstats
😋🎋 Welcome 'Kite-Eating Tree'!
🙌🎥 gif courtesy of @pdalgd!
🤔👇 Curious about the other R release name origins? Check out our post!
🔗 https://t.co/b7XkQKwHpMpic.twitter.com/J1UNks276A

— Lucy D’Agostino McGowan (@LucyStats) November 30, 2017
  • Youtube:
  • Vimeo:
  • Github Gist:
  • Instagram:

A post shared by Bjørn Erik Pedersen (@bepsays) on

Figure:

Tables

There are several ways to present tables.

  • Simple tables are easy to create. Header and rows must be on two lines, and column alignment is determined according to the position of the header relative to the line under it. Tables must be surrounded by empty lines and an optional caption may be added above or below the table, starting with Table: or : (which is stripped off).
Demonstration of a simple table with caption.
RightLeftCenterDefault
12121212
123123123123
1111
  • The header may be omitted, but then, the ending line is mandatory.
A table without header.
12121212
123123123123
1111
  • Multiline tables start and end with a line of dashes. Cells are separated by spaces (in case of a single row table, add the empty line too, otherwise, the table is interpreted as a sinlge-line table). In multiline tables, the writer tries to respect the relative size of the columns that appear in the markdown document.
A multiline table.
CenteredHeaderDefaultAlignedRightAlignedLeftAligned
Firstrow12.0* Example of a row thatspans multiple lines.
Secondrow5.0* Here’s another one. Notethe blank line betweenrows.
  • Headers can be omitted too in multiline tables (note that this could be used as a simple formatting hack to place –short– material on several columns!):
Here’s a multiline table without headers.
Firstrow12.0Example of a row thatspans multiple lines.
Secondrow5.0Here’s another one. Notethe blank line betweenrows.
  • Grid tables (rows with = separate headers and can be omitted for headerless tables). Apparently, more formatting is allowed in gridded tables, like list items:
Sample grid table.
FruitPriceAdvantages
Bananas$1.34
  • built-in wrapper
  • bright color
Oranges$2.10
  • cures scurvy
  • tasty
  • Pipe tables look like this (beginning and end pipes are optional, and optional colon indicates alignment, header can be omitted but not the lines, and finally, although ugly, pipe do not need to align). Note that table characters like | cannot appear in the table and this form does not support multiline tables. The semicolumn :may be used to indicate alignment inside each column, but it is an optional feature.
A typical pipe table.
RightLeftDefaultCenter
12121212
123123123123
* 1111

Equations

  • Inline equations like (frac{1}{n} sum_{i=1}^{n} x_{i} + beta), or (f(alpha, beta) propto x^{alpha-1}(1-x)^{beta-1}).

  • Display equation

[ frac{1}{n} sum_{i=1}^{n} x_{i} + beta ]

Here is a more complex example spanning on several lines:

[ begin{aligned}dot{x} & = sigma(y-x) dot{y} & = rho x - y - xz dot{z} & = -beta z + xyend{aligned}]

If you feel difficult to write LaTeX equations, there are inline LateX equation editors like this one, and you don’t need to install anything on your computer to used them. Also, there is a R Studio addin provided with the bookdown R package to ease entering LaTeX equations in your R Markdown document.

Knitr chunks

The R package knitr is used to insert R code withing your Markdown document, which makes altogether an R Markdown document, usually with the .Rmd extension. Go to knitrhomepage for more details.

R chunks

  • A few R commands:
  • Normal output versus message versus warning versus error:
  • R chunk with option to generate a plot5:

Figure 1: An example figure generated by R, from the cars dataset.

My plot is here.

  • Another plot:

Figure 2: Distance in function of speed for the cars data set.

I can now reference this figure in the text (see this plot).

  • R chunk with option to generate a table :
Table 1: The first few lines of the iris data set.
Sepal.LengthSepal.WidthPetal.LengthPetal.WidthSpecies
5.13.51.40.2setosa
4.93.01.40.2setosa
4.73.21.30.2setosa
4.63.11.50.2setosa
5.03.61.40.2setosa
5.43.91.70.4setosa

Now, I can refer to this table (see this Table).

Tables using xtable

The xtable R package offers an alternative to output well-formatted tables in an R Markdown document:

gradesexdisadvgethnictytlimth
16MYESHISPANIC43
27MNOBLACK88
35FYESHISPANIC34
43MYESHISPANIC65
58MYESWHITE75
65MNOBLACK74
78FYESHISPANIC72
84MYESBLACK79
96MNOWHITE88
107MYESHISPANIC87

Tables using pander

The pander package can output various objects in pandoc:

Sepal.LengthSepal.WidthPetal.LengthPetal.WidthSpecies
5.13.51.40.2setosa
4.93.01.40.2setosa
4.73.21.30.2setosa
4.63.11.50.2setosa
5.03.61.40.2setosa
5.43.91.70.4setosa

Tables using flextable

Blogdown Rmd

The flextable package allows for fine customization of the formatted table:

cyl

am

avg

4

0

22.90000

4

1

28.07500

6

0

19.12500

6

1

20.56667

8

0

15.05000

8

1

15.40000

There are many other packages to output well-formatted tables from R objects, like: stargazer, table1, tables, formattable, htmlTable, huxtable, kableExtra, pixiedust, tangram, texreg, ztable, etc.

Inline R expressions and special chunks

  • Inline R expression like 2, or R version 3.6.3 (2020-02-29).

  • Rcpp code chunks can also be included in your document:

Because fibonacci was defined with the Rcpp::export attribute it can now be called as a normal R function:

  • An R chunk that is displayed, but not executed:
  • A Python chunk:

Icons

You have both the font awesome, and the themify icons. You need to create an object of class “fa fa-xxxx”, or “ti-xxxx”, where “xxxx” is an icon in the collection. Here is an example from font awesome , and here is one from themify: . You can use these icons everywhere!

Citations

Thanks to Pandoc, it is rather easy to insert citations in your text. First, you need to specify a bibliography file in a YAML section. A number of formats are supported, but to remain compatible with LaTeX, use BibTeX (.bibtex) or BibLaTeX (.bib) format only. Note that the bibliography folder, like for figures is two folders ahead in the relative path, i.e., ../../bibliography/<my-file.bib>.

The file we use here is named bibliography.bib. It is enough to refer to it in a YAML section. However, we will also add more reference to the bibliography later on. So, we first copy this file into bibliography-full.bib and then, we refer to the later file instead.

  • A references field can also be included in a YAML section for self-contained bibliography (and you can use both at the same time!).
  • The R package knitcitations uses pandoc citations, but enhances its mechanisms by allowing to add citations by DOIs or URL and by linking to cited papers directly. You need to start loading the package and clean up citations.

You can use references citations contained in your bibliography inside square brackets, separated by semicolons and each citation must be composed using @ + citation identifier. For instance (Greenwade 1993; Fenner 2012), or (see Fenner 2012, pp. 12–17; also Greenwade 1993, ch. 2). Use a minus sign before the reference to suppress mention of the author: as Greenwade (1993) indicated, “bla bla”. You can also write the inline citation this way: Fenner (2012, p. 10) says “bla”.

Finally, you can include citations in the references without citing them by using a nocite entry in a YAML block:

By default, the Chicago author-date format is used by Pandoc, but you can use a different style by specifying a CSL 1.0 style in a csl metadata entry in a YAML block. The RStudio rmarkdown site indicates two interesting pages to get CSL files: CSL official repository and Zotero styles page that allows easy browsing. Here, we use the Marine Biology style.

As already mentioned, an addition to this mechanism is provided by the knitcitations package that allows to build citations from DOIs, or URL into Pandoc-compatible citations. The question of independent .bib file, and/or need for an Internet link to compile the document is discussed here http://blog.martinfenner.org/2013/06/19/citations-in-scholarly-markdown/.

One big lack in this approach is no link between the citation and the reference.

Now for knitcitations citations… We can add a citation by DOI (Abrams et al. 2012), or Boettiger and Hastings (2013). Since a citation like name_year is automatically created, one do not need to recite the same items by DOI, but one can cite like this (Abrams et al. 2012), which should be the same as (Abrams et al. 2012). Finally, one can also cite R bibentry objects directly, like (Xie 2014, 2015, 2020). All these approaches are combinable with traditional pandoc citations, providing these citations are already included in the .bib file.

Finally, don’t forget to generate the complete .bib file by appending the following last R chunk into your document in order to add the knitcitations in your document properly:

Note how the references are included automatically at the end of the document. Do not forget to put an adequate header by yourself!

References

Abrams PA, Ruokolainen L, Shuter BJ, McCann KS (2012) Harvesting creates ecological traps: Consequences of invisible mortality risks in predatorprey metacommunities. Ecology 93:281–293. https://doi.org/10.1890/11-0011.1

Boettiger C, Hastings A (2013) No early warning signals for stochastic transitions: Insights from large deviation theory. Proceedings of the Royal Society B: Biological Sciences 280:20131372. https://doi.org/10.1098/rspb.2013.1372

Fenner M (2012) One-click science marketing. Nature Materials 11:261–263. https://doi.org/10.1038/nmat3283

Greenwade G (1993) The Comprehensive Tex Archive Network (CTAN). TUGBoat 14:342–351

Xie Y (2020) Knitr: A general-purpose package for dynamic report generation in r

Xie Y (2015) Dynamic documents with R and knitr, 2nd edn. Chapman; Hall/CRC, Boca Raton, Florida

Xie Y (2014) Knitr: A comprehensive tool for reproducible research in R. In: Stodden V, Leisch F, Peng RD (eds) Implementing reproducible computational research. Chapman; Hall/CRC

  1. This is my simple footnote.↩︎

  2. Footnotes can span on multiple paragraphs, providing you indent them with four spaces:

    • A list item

    Another paragraph belonging to the note.↩︎

  3. Inline footnotes are easier to write right in your text, but they can only span on a single paragraph.↩︎

  4. Note that you cannot include the number inside the link, unfortunately.↩︎

  5. Do not use underscore _ in the label of your chunk to use it as a link!↩︎

Welcome

Hi! Hello! Welcome. Bienvenidos.

About 3.5 years ago, I wrote my first blog post and published it on my first website. Since then, that single post has been viewed over 27,557 times. That may not seem like a lot to some folks, but it is to me! Even more meaningful to me, though, has been watching the launches of so many people’s personal websites.

However, the process of creating and maintaining a Hugo website using blogdown was not always pain-free. Sometimes we have Hugo “improvements” to thank, other times your Hugo theme is at fault, and sometimes we could blame blogdown. Regardless of where the pain came from, there was definitely room for improvement.

Here are some great blog posts that document pretty common user experiences and frustrations:

All of this, combined with my own experiences teaching and using blogdown for over 3.5 years led me to…my giant blogdown wishlist. I had a lot of ideas to help beginners get started, but just as important, to improve the quality of life for existing users. You can see my mega-wishlist that Yihui Xie (the blogdown conceptor and author) asked me to share with him: https://github.com/rstudio/blogdown/issues/476

I’m very happy to report that our team has been working very hard to address these issues, and many others raised by users, to make blogdown easier to learn and use. Just in time for the new year, we have a new and improved release of the blogdown package for you to test. I know a lot of folks are itching to introduce themselves into online communities and conversations, so I thought it would be fun to take my original blogdown post, and trace the same process of building a Hugo website with the same theme (now named “Wowchemy” instead of Hugo Academic- don’t get me started).

So if you are feeling fearless and want to live on the bleeding edge, read on to give the development version of blogdown a spin along with me.

tl;dr

If you already know what you are doing, this entire post can be condensed into just a few lines of code:

The above sequence is a slightly more advanced workflow than the steps I follow below, but is fairly magical- attempt at your own risk! For everyone else, read on…

Pre-requisites

Getting any website up and running with all the moving parts (RStudio, GitHub, Hugo, Netlify) can take a few tries. In this post, I’m passing along what works for me, and the workflow that I use when I teach Hugo website development. Everyone’s mileage may vary, though, depending on your operating system and your approach.

For this blog post, I’m assuming you have basic familiarity with:

  • R,
  • the RStudio IDE, and
  • GitHub.

If that is not you, you will need to work through Happy Git with R by Jenny Bryan et al. first, then come back here when you are ready.

Since the development version of blogdown is currently only available on GitHub, you may need to setup a GitHub Personal Access Token to install it.

In my original 2017 post, I mentioned that at that time, I was a new mom, and just in the process of writing all that up, I filled up my tea mug twice with ice cold water, and filled my water bottle with scalding hot water. This time around isn’t too different! Fast forward to 2020: there is a global pandemic, I’ve been under stay-at-home orders with a child under 5 years of age at home for months. So buckle up 🤠

I’ve included code chunks below using the rstudioapi package to help you navigate to the right file at the right time. Hugo sites have a dizzying and heavily nested directory structure! You’ll need to run install.packages('rstudioapi') to use those code chunks, but you can also navigate on your own to the file you need too.

Step 0: Set your intentions

During workshops, I try to set aside some time at the start for folks to set their website intentions. This might feel a bit like navel-gazing, but trust me here. I know you just want to jump in and get started!

Hear me out though, and don’t skim or skip this step. The process of actually building and deploying a personal site can be complicated, and it is easy to get lost in the weeds.

It is very easy to run out of steam when it is time to do the most fun and important piece: dreaming about the kind of site you want to make!

Do this right now! Take 10 minutes to set your website intentions—grab a pen and notepad and a cup of 🍵 and read on…
Blogdown

1. Content

Hugo is made for blogs. But, in addition to a blog, the starter-academic theme provides a unique system of widgets. You can have one or many widgets on pages in your site. I like to think of widgets like Mr. Potato Head where:

  • Each page is a potato head, and
  • Each widget is a piece you could place on the potato head.

Take the homepage for example, seen on the Academic demo site. Each band or section you see is a widget. Widgets can be stand-alone pages, or can be combined on a single page.

Examples:

  • Multiple widget page: my resume and about pages
  • Single widget page: my projects
Look at the Academic demo site and write down some widgets you see that you like, and the ones you definitely don’t.

2. Menu

Now that you have a sense of the content you want, how do you want a visitor to be able to explore your content? I typically recommend limiting the top navbar to 5 links max (excluding the search icon).

Use some of my favorite personal sites (that do not use our theme) as inspiration too:

Think about how the menu “prewires” you to know what to expect as you dig deeper into their site. How do you want people to get to know you online?

Write down up to 5 items to appear in your upper navbar.

3. Homepage

This is the first page a visitor lands on when they find your site. Think of it like a welcome mat. Do you like a single page site where you scroll and see everything on one page? Or do you prefer a short and sweet homepage? Do you want a photo and a bio to be the first thing visitors see? What else?

Here are some examples of personal websites built with the Hugo Academic theme to inspire you:

Write down the widgets you want to see on your homepage. It can be one, or many.

OK, keep these notes handy! We are ready to make something.

Step 1: Create repo

  1. Go online to your GitHub account, and create a new repository (check to initialize with a README but don’t add .gitignore- this will be taken care of later). For naming your repo, consider your future deployment plan:

    • Netlify. I recommend using Netlify to both build and host your site. In this case, you can name the repository anything you want!

    • GitHub Pages. I recommend Netlify over GitHub Pages for blogdown/Hugo sites. But, if you want to host your site with GitHub Pages, you should name your repository yourgithubusername.github.io (so mine would have been apreshill.github.io). This post won’t be able to help you with publishing.

You can see some of the repo names used by members of the rbind organization here.
  1. Go to the main page of your new repository, and under the repository name, click the green Clone or download button.

  2. Choose either SSH or HTTPS (if you don’t know which, choose HTTPS). Choose by clicking on the clipboard icon to copy the remote URL for your new repository. You’ll paste this text into RStudio in the next section.

Step 2: Create project

We just created the remote repository on GitHub. To make a local copy on our computer that we can actually work in, we’ll clone that repository into a new RStudio project. This will allow us to sync between the two locations: your remote (the one you see on github.com) and your local desktop.

Open up RStudio to create a new project where your website’s files will live.

  1. Click File > New Project > Version Control > Git.

  2. Paste the copied URL from the previous step.

  3. Be intentional about where you tell RStudio to create this new Project on your workstation.

  4. Click Create Project.

Step 3: Create site

  1. The latest version of blogdown will not be available on CRAN until January 2021, but you can install the development version from GitHub with:

  2. Let’s use our first blogdown function to create a website with the Hugo Wowchemy “starter-academic” project:

  3. You should now see something like this. Take a moment to read through these messages - importantly, it tells you how to start and stop the server so you can preview your site. Importantly, when you come back to your project, note that you can use blogdown::serve_site() or the “Serve Site” addin to preview it locally.

    Let’s select y to let blogdown start a server for us.

    Exciting, isn’t it? Now, don’t trap your site in the RStudio Viewer pane. Let it out! Click to “Show in new window” (to the right of the 🧹 icon) to preview it in a normal browser window. When you do that, you’ll be re-directed to the site’s main homepage. Let’s find our way back to the R Markdown post. Click on Posts > Hello R Markdown to read it:

    This is what blogdown gives you- everything else in the site is given to you by Hugo and your Wowchemy Hugo theme. But this post, and your ability to see output and plots rendered with is what blogdown adds!

Step 4: Create content

Let’s use more R Markdown 🎉

Blogdown allows you to create new two kinds of R Markdown posts that are knittable:

  • .Rmd 🧶 to .html or

  • .Rmarkdown 🧶 to .markdown

Once knitted, both are then previewable in your Hugo site.

I used to agonize over which file extension to use. But now I am squarely in .Rmarkdown camp with Maëlle- I like knitting to .markdown and wish this was easier in blogdown; see: https://github.com/rstudio/blogdown/issues/530

Use the console to author a new .Rmarkdown post; I’ll name my post “Hi Hugo”:

This takes the path to where you want your post to live, relative to the content/ folder (so that piece of the path is assumed, rightly so!). In the Academic theme, the example site organizes blog posts into the content/post/ folder, but the name of this folder varies across Hugo themes.

A rule that is true 90% of the time: folders in content/ are singular, not plural— ✔️ post; ❌ posts

You can add an option to your .Rprofile to save these settings so you don’t have to remember them:

Then add the blogdown options to that file, save, and RESTART YOUR R SESSION for changes to take effect:

Always restart your R session after editing your .Rprofile for changes to take effect. Don’t forget to run serve_site() after a restart.

If you look in your Files pane, you can see that this creates a folder with the date and the “slug” name of my post ('hi-hugo'). The actual R Markdown file is named index.Rmarkdown.

This is a Hugo page bundle. Each post gets its own bundle, or folder. Inside the post bundle is where all your static images, static data files like .csv files should go.

In the post itself, use the relative file path like:

Let’s look at the index.Rmarkdown. We’ll knit this .Rmarkdown to a .markdown file. You may 🧶 knit 🧶 freely now in blogdown!

To knit an .Rmarkdown post, you can either:

  1. Use the Knit button to knit to the correct output format, or

  2. Use the keyboard shortcut Cmd+Shift+K (Mac) or Ctrl+Shift+K (Windows/Linux).

After knitting, you should now see:

Go ahead and add an R code chunk like:

After you edit your .Rmarkdown post, knit. Note that knitting automatically saves the file for you. You also can just save the file without knitting- this is good for when your code still needs work and won’t run as is.

The most important thing here is to realize that the act of knitting creates an index.markdown file in the same post bundle as index.Rmarkdown. Because Hugo doesn’t know R or R Markdown, The index.markdown version is what then feeds into the Hugo static site generator.

Try it again! Add another R code chunk like:

Knit, and you should see something like:

Many R Markdown output options for HTML documents are not going to be possible here, like tabbed sections, floating table of contents, the code_download button, etc. Also, HTML widgets are a little dicey currently.

This is a single page. It is made with R Markdown, and happens to be a blog post, although you can use R Markdown to create content for any other content section too.

If you want a featured image to accompany your post and show up on your listing page (the clickable list of all your posts), you’ll want to add an image with the word featured in the filename:

Workflow

My workflow in RStudio at this point (again, just viewing locally because we haven’t deployed yet) works best like this:

  1. Open the RStudio project for the site.

  2. Start the Hugo server using blogdown::serve_site() (only once due to the magic of LiveReload).

  3. View site in the RStudio viewer pane, and open in a new browser window while I work.

  4. Select existing files to edit using the file pane in RStudio.

  5. After making changes, save if a plain .md file, or if working with an .Rmd or an .Rmarkdown document, knit to preview! You can now use the Knit button to knit to the correct output format. You can also use the keyboard shortcut Cmd+Shift+K (Mac) or Ctrl+Shift+K (Windows/Linux).

  6. The console will detect the change (it will print Change detected, rebuilding site.), the viewer pane will update, and (in a few seconds) your local view in your browser will also refresh. Try to avoid hitting the refresh button in your browser.

  7. When happy with changes, add/commit/push changes to GitHub.

Having blogdown::serve_site running locally with LiveReload is especially useful as you can immediately see if you have totally screwed up. For example, in editing my about.md file, this error popped up in my console after making a change and I was able to fix the error right away:

Using GitHub

Let’s go ahead and push our changes to GitHub. First, let’s make a .gitignore file:

Add this content:

Check yourself before you wreck yourself

Let’s use blogdown to check this file before we do our first commit:

You should see something like:

You have a [TODO] item- go ahead and add public and resources on their own lines in your .gitignore file. We’ll be configuring Netlify to build our site shortly, so go right ahead while the file is open.

While we are at it, let’s check out our content too:

You may notice a few pieces of content are flagged as draft. This is good to know! Read up on drafts in Hugo here.

Our checks are pretty clean, so you can freely add/commit your project files to GitHub. You now should have the basic mechanics of your site working.

Step 5: Publish site

Thus far, we’ve only been previewing our site locally, then pushing the source files (but not the built site) to GitHub. This workflow works, but I assume you want to ride this bike. Let’s skip the training wheels — we are going one step more advanced by using GitHub with Netlify now.

Note that you could use blogdown::build_site(), then publish the public/ folder using Netlify drag & drop. Watch this webinar called “Sharing on Short Notice” to learn more - but this is a less advanced workflow.

Blogdown Book

To get started using Netlify for real (which has a free plan that should largely cover recreational blogging use!):

  1. Go online to Netlify.

  2. Click on the Sign Up button and sign up using your existing GitHub account (no need to create another account).

  3. Log in, and select: New site from Git > Continuous Deployment: GitHub.

  4. From there, Netlify will allow you to select from your existing GitHub repositories. You’ll pick the repo you’ve been working from with blogdown. Leave all settings as they are and select Deploy Site.

You should see something like this:

When it is done, you can click on the link to your new site! And the most magical thing of all, every time you push any changes to your site to GitHub, Netlify will detect the push, re-build, then update your published site. It’s a good thing. It’s called continuous deployment, and it is the main reason to use Netlify for a blogdown site.

With a new site, Netlify will deploy your site and assign you a random subdomain name of the form random-word-12345.netlify.app. Mine was particularly unfortunate, with the random word garbage-collector-janice. You should know that you can change this; I changed mine to apreshill.netlify.app. Do this by navigating to your site on Netlify, then click on Settings. Under Site information, click on the Change site name button.

Whether you change your Netlify site name or use the random one, go back to your configuration file and cchange the baseurl there to match where Netlify is publishing your site:

You actually have most of the necessary wiring laid out for you already in your repo, which is why this worked. Our site has a netlify.toml file, which sets us the necessary settings for letting Netlify build our site for us and then publish it. You can read more about this file here, and check it out using:

Now, back in your local blogdown project, let’s check this file with blogdown:

I recommend going with Option 1 here, so follow that [TODO] and then run the function again to get a clean check.

When you are ready to deploy, commit your changes and push to GitHub! Watch as your site rebuilds 🎉

To get an *.rbind.io URL, follow these instructions.

Anytime you change your subdomain name, you need to update the baseurl in your config.toml file (so I changed mine to baseurl = “https://apreshill.netlify.com/').

Step 6: Sculpt site

Now, we’ll leave blogdown and R Markdown behind. We’ll just be using Hugo and Wowchemy (I think it is said like alchemy? Why??) to build your personal website.

Let’s start by running another blogdown check to check_hugo():

All set! We’ve already checked out our Netlify set-up ✔️ If you wish to clean up your local Hugo installations, check out:

Configure your site

Let’s start with the last thing you typically do to your home- decorate.

Open up the file config/_default/params.toml. Play with any of these configurations, but especially fonts/themes.

If you want deeper customization of the styling, you can create a new CSS file assets/scss/custom.scss and use it to override any existing styles. You can see mine here; heavily borrowing from my former intern Desirée De Leon!

While you are at it, edit the other configuration files:

  • You can also view my config.toml file

Remember our menu intentions? Go ahead and edit those too:

Let’s run a blogdown check on the configuration file before we leave:

Looks like we have a few [TODO] items to add to our config.yaml file:

Goodbye Nelson B.

Let’s say goodbye to Nelson Bighetti. Everything in this single markdown file populates what is called the about widget; a customized one looks like this:

Find and open the file content/authors/admin/_index.md:

Edit the YAML metadata to change:

  • The icons and where they link to

  • Your current role and organization

  • Your interests

  • Your education

The text under the YAML is your bio; you can use markdown here. Add an avatar.jpg file too (it must be named this) to the same folder.

Prune widgets

Remember how we started with thinking about your content? We are ready to prune out some of our unwanted widgets.

Recall that on the Academic demo site, the entire home page is filled with widgets! The default example site is the exact same as the demo. It sets almost every available widget to active to show you the range of what you could do.

Deactivating the widgets you don’t need and only activating the ones you want will help you avoid having your home page feel like the 💀 “scroll of death,” as my friend Jackie Wirz called it.

Remember my Mr. Potato Head analogy? The home page is your most prominent potato, and the widgets are all the pieces you could use.

Each widget you see is a *.md file in the content/home/ folder. The metadata at the top helps you configure each widget; namely whether it is active (true or false) and the widgets weight (ordering, actual numbers doesn’t matter- only relative to the other weights).

For example, to turn off the hero widget, use this code in your console and set active = false:

Take about 10 minutes about try out turning widgets off and on, and changing their order to see what you like!

You can also delete a widget file. You can always recover *.md widget files by going into your themes/hugo-academic/exampleSite/content/home/ folder.

For my own site, I use 4 main home page widgets:

  1. about (photo / icons / bio / interests / education)
  2. slider (used to showcase some feedback from my workshops)
  3. posts (set to show only the most recent)
  4. talks (set to show only the most recent)

Transplant widgets

If you opted for a more streamlined home page with fewer widgets, you may experience widget pruning regret. Many are very useful, and you may wish to use widgets on other pages that are not the home page. In this theme, this is possible! Even if you turn off a widget on the home page, you can create what is called a widget page and add or even combine widgets there. I make heavy use of widget pages in my own site. Here are the steps (following the docs):

Blogdown R
  1. Create a new folder in content/; let’s call it resume

  2. Inside content/resume/, add a file named index.md

  3. Populate content/resume/index.md with a YAML, like this:

The very critical line here is the type: widget_page—this sets you up to now copy over widgets from content/home/ in this new folder.
  1. Copy the widget *.md files you’d like to use into this content/resume/ folder. Edit their metadata (weights, other info), and be sure to set active = true. For my own resume, I copied the experience and accomplishments widgets over.

  2. If you want to access this new widget page from your top navbar, open up your config/_default/menus.toml and add it there, like:

You can link to any specific widget by taking your baseurl and appending /#{name-of-widget}, so /#slider links to my homepage slider. And /resume/#accomplishments links to my honors & awards

Let’s run one final check, which wraps all 5 checking functions we’ve used so far into a single final checklist:

This is immensely comforting to me; read more about these new checking functions here.

We made it!

Blogdown Rstudio Connect

At this point, you should be up and running with blogdown, GitHub, and Netlify. You now have the scaffold up and ready for your ideas, your style, and your voice. If you made it this far, please share your site- I’d love to see it!