Tuesday March 26th, 2019

Quick links

What is a Blog?

The requisites of our blog

R Markdown

R Markdown is a file format to make dynamic documents in R.

An R Markdown document is written in
markdown (an easy-to-write plain text format)
and contains chunks of embedded R code.

Example:

        # Plotting a simple Histogram 
        
        We generate a number `n=50` of 
        **Normal** disributed random variables 
        and plot them as an histogram
        
        ```{r}
         hist(rnorm(50))
        ```   

Plotting a simple Histogram

We generate a number n=50 of Normal disributed random variables and plot them as an histogram

blogdown + RStudio

blogdown is a package in R, developed by Yihui Xie (also author of knitr), that facilitates to build blogs with R Markdown in RStudio.

It is mainly tailored for the static generator Hugo, but following the author of the package, we tweak it to make it work with the static generator Jekyll.

Book published on 2017:

“blogdown: Creating Websites with R Markdown”
by Y. Xie, A. P. Hill, A. Thomas

it is also available on-line

git + GitHub

  • Create a repository, for example name it my_blog,
    and initialize it with a README.md

  • Go to Settings -> GitHub Pages
    • set Source to master branch
    • select a Jekyll theme, for example to Minimal
  • Edit your repository in the main page
    and set its website link

To manipulate locally repositories from your coputer, you need to download and istall git.

Associate RStudio with Github

  • Then enable version control in RStudio by going to
    Tools -> Global Options... -> Git/SVN

  • There write the location of the git executable

  • Then Create RSA key... or select one if you already have them.

  • Then open the Terminal by going to
    Tools -> Shell...

  • and enter your details for your commits

    git config --global user.email "my.email@university.edu"
    git config --global user.name "my.username"

Create a new RStudio project

  • File -> New Project... -> Version Control -> Git
  • Type the url of your GitHub repository
  • Select a name and a location for your RStudio project

Then

  • assure to have the package blogdown installed

    ## Install from CRAN
    install.packages("blogdown")
    ## Or, install from GitHub
    if (!requireNamespace("devtools")) install.packages("devtools")
    devtools::install_github("brdauria/blogdown")

Configure for Jekyll on GitHub Pages

  • Set the file content _config.yml as follows

    title: My first blog
    description: >- # this means to ignore newlines until "email:"
      "This blog has been creatged during the mini-course 
      'Blogging with R' by Bernardo D'Auria on Tue March 26th, 2019"
    email: my.email@university.edu
    
    # Build settings
    markdown: kramdown
    exclude: ['*.Rmd'] # this is important to use with RMarkdown
    theme: minima
    plugins:
      - jekyll-feed # to serve posts
  • Create the folder _posts

Configure for Jekyll on GitHub Pages

  • Create the file Gemfile

    source "https://rubygems.org"
    
    # To upgrade, run `bundle update github-pages`.
    gem "github-pages", group: :jekyll_plugins
    
    group :jekyll_plugins do
      gem "jekyll-feed"
    end
  • Add to .gitignore

    _site/
    .sass-cache/
    .jekyll-cache/
    .jekyll-metadata

Add an index.html page

  • Create the file index.Rmd

       ---
        layout: home
        title: "Welcome to my Blog"
       ---
    
        ```{r, echo=FALSE}
        library(ggplot2)
    
        ## Plot
        g <- ggplot(mpg, aes(cty))
        g + geom_density(aes(fill=factor(cyl)), alpha=0.8) + 
            labs(title="Density plot", caption="Source: mpg", 
                 x="City Mileage", fill="# Cylinders")
        ```
    
  • Run knitr::knit('index.Rmd')

Make your FIRST post

  • Create the file _posts/2019-03-01-HelloWorld.Rmd

        ---
        title: "Hello World!"
        author: "Bernardo D'Auria"
        date: "2019-03-01"
        ---
        Let us sum `1+1` by **R**.
    
        ```{r}
        1+1
        ```
    
  • Run

      owd = setwd('_posts/'); 
      knitr::knit('2019-03-01-HelloWorld.Rmd'); setwd(owd);

The blog works!

  • Commit and Push

Now going to the url of the GitHub Pages of our repository,

the blog WORKS!

To run it locally:

You need to have Jekyll installed

  • run bundle install
  • run bundle exec jekyll serve
  • open in the browser the url http://127.0.0.1:4000/

Jekyll

Jekyll is a simple, blog-aware, static site generator perfect for personal, project, or organization sites.

Jekyll is the engine behind GitHub Pages, which you can use to host sites right from your GitHub repositories.

  • find here the instructions to install for different platforms

  • it may require to download and install a more recent version of Ruby language

  • assure to have run the command

    bundle install
  • Example in class:
    run jekyll new . --force in the project folder

Make Jekyll the generator for blogdown

  • create the hidden file .Rprofile in the project directory

    options(
       blogdown.generator = 'jekyll', blogdown.method = 'custom',
       blogdown.subdir = '_posts', servr.daemon = TRUE,
       blogdown.base.dir = 'assets/figures/',
       blogdown.base.url = '{{ "assets/figures/" | absolute_url }}'
     )
     # IMPORTANT: please leave this comment line!

Make Jekyll the generator for blogdown

  • create a new folder, name it R, containing two files:
    - build.R
    - build_one.R

    You can download them by clicking on them
    or you can look for them in the R directory in the brdauria/blogdown-jekyll repository

  • make sw/hd link config.yaml to _config.yml

    ln -s _config.yml config.yaml # on MAC/Linux
    mklink config.yaml _config.yml # on Windows

Make your SECOND post

  • Select in the toolbar Addins -> New Post
  • Type the following informations

    Title:    "Hello Jekyll!"
    Author:   "Bernardo D'Auria"
    Date:     2019-03-05
    Category: graphs
    Format:   R Markdown (.Rmd)
  • Click on Done

A new file named 2019-03-05-hello-jekyll.Rmd
will be added in the _posts directory
and it will be opened for modifications.

Make your SECOND post

  • Modify the YAML header of the post as follows

    ---
    title: Hello Jekyll!
    author: "Bernardo D'Auria"
    date: '2019-03-05'
    slug: hello-jekyll
    categories:
      - graphs
    tags: []
    
    layout: post
    ---

Make your SECOND post

  • and the body as the following

    This is my first plot that cointains an R graph
    
    ```{r}
    library(ggplot2)
    ggplot(iris,aes(x=Sepal.Width,y=Sepal.Length)) + geom_point()
    ```
    
    and an external picture
    
    ![colored cats](https://raw.githubusercontent.com/brdauria/codingclubuc3m_talk/master/docs/images/cats.jpg)
    
    ```

you can download the file here 2019-03-05-hello-jekyll.Rmd

Make your SECOND post

  • build and serve your blog
    Addins -> Serve Site

    and in the Viewer Pane
    you should see your blog

    WORKING with PICTURES!

  • commit and push

    and you should see your blog also in

    WORKING in INTERNET!

Needing some formulas

What we finally miss is to include in our posts some
nice formulas

  • like this \(\sqrt{\frac{9}{4}} = \frac{3}{2}\)

  • and this

    \[ \int_0^{\infty} e^{-x^2} dx = \frac{\sqrt{\pi}}{2} \]

So let us prepare our blog and make our third post!

Jekyll directory structure

.
├── _config.yml
├── _data
|   └── members.yml
├── _drafts
|   ├── begin-with-the-crazy-ideas.md
|   └── on-simplicity-in-technology.md
├── _includes
|   ├── footer.html
|   └── header.html
├── _layouts
|   ├── default.html
|   └── post.html
├── _posts
|   ├── 2007-10-29-post-2.md
|   └── 2009-04-26-post-1.md
├── _sass
|   ├── _base.scss
|   └── _layout.scss
├── _site # generated by jekyll and containing the website
├── .jekyll-metadata
├── Gemfile
├── Gemfile.lock
└── index.html # can also be an 'index.md' with valid front matter

The theme minima directory structure

  • run the command

    system2('bundle', 'show minima')

    to get the minima gem location.

  • then

    list.files('/usr/local/lib/ruby/gems/2.5.0/gems/minima-2.5.0')

The theme minima directory structure

/usr/local/lib/ruby/gems/2.5.0/gems/minima-2.5.0
├── _includes
|   ├── disqus_comments.html
|   ├── footer.html
|   ├── google-analytics.html
|   ├── head.html
|   ├── header.html
|   ├── icon-github.html
|   ├── icon-github.svg
|   ├── icon-twitter.html
|   ├── icon-twitter.svg
|   └── social.html
├── _layouts
|   ├── default.html 
|   ├── home.html
|   ├── page.html
|   └── post.html
├── _sass
|   ├── minima
|   |   └── ...
|   └── minima.scss
├── assets
|   ├── main.scss
|   └── minima-social-icons.svg
├── LICENSE.txt
└── README.md

Customize the blog to allow formulas

  • in the folder _include create mathjax.html

    {% if layout.mathjax or page.mathjax %}
    <!-- https://docs.mathjax.org/en/
                latest/configuration.html#local-config-files -->
    <script type="text/javascript"
            src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.4/
                 latest.js?config=TeX-AMS-MML_HTMLorMML,
                 {{ 'assets/js/MathJaxLocal.js' | absolute_url }}">
    </script>
    {% endif %}

    It contains Liquid templating syntax! See here for more!

  • in the folder assets/js create MathJaxLocal.js

    # TOO BIG to include here. Please click to download!

Customize the blog to allow formulas

  • in the folder _layout create mpost.html

    ---
    layout: post
    mathjax: true
    ---
    
    {% include mathjax.html %}
    
    {{ content }}

Make your THIRD post

  • Select in the toolbar Addins -> New Post
  • Type the following informations

    Title:    "Hello Math!"
    Author:   "Bernardo D'Auria"
    Date:     2019-03-15
    Category: math
    Format:   R Markdown (.Rmd)
  • Click on Done

A new file named 2019-03-15-hello-math.Rmd
will be added in the _posts directory
and it will be opened for modifications.

Make your THIRD post

  • Modify the YAML header of the post as follows

    ---
    title: Hello Math!
    author: "Bernardo D'Auria"
    date: '2019-03-15'
    slug: hello-math
    categories:
      - math
    tags: []
    
    layout: mpost
    ---

Make your THIRD post

  • and the body as the following

    This is my first plot that cointains  
    nice formulas
    
    - like this 
    \\( \sqrt{\frac{9}{4}} = \frac{3}{2} \\) 
    
    - and this
    
      $$ \int_0^{\infty} e^{-x^2} dx = \frac{\sqrt{\pi}}{2} $$

you can download the file here 2019-03-15-hello-math.Rmd

  • see immediatelt the preview in the Viewer Pane

  • commit and push to check it in Internet

Working with Themes

Jekyll is very powerful for

  • its modularity

  • its themes

However this has a cost:

  • things may work slightly different from theme to theme

therefore there is some extra work to do!

We are going to work with: Minimal Mistakes theme

Minimal Mistakes theme

  • remove index.md and write index.html as follows:

       ---
        layout: home
        author_profile: true
       ---
  • add to Gemfile

       group :jekyll_plugins do
        ...
        gem "jekyll-include-cache"
      end

Minimal Mistakes theme

  • add to _config.yml this

       github: [metadata] # important to use remote_theme
       minimal_mistakes_skin: dark
       remote_theme: "mmistakes/minimal-mistakes@4.15.2"
       paginate: 5
       plugins:
        ...
        - jekyll-include-cache
        - jekyll-paginate

Minimal Mistakes theme

  • add to _config.yml and this

        # Front Matter Defaults:
        defaults:
          # _posts
          - scope:
              path: ""
              type: posts
            values:
              layout: single
              author_profile: true
              read_time: true
              comments: true
              share: true
              related: true
  • then Commit and Push

More resources

Thanks