Home » Posts tagged 'Markdown'

Tag Archives: Markdown

Post to WordPress through R Markdown

Blogs are a great communications tool. Finding a way to post to WordPress through R Markdown can be a nice efficiency hack. This post documents a method for generating WordPress posts through RStudio. It uses the RWordPress package by Duncan Temple Lang. This tutorial is basically a scaled-down version of Peter Bumgartner’s excellent tutorial.

At the time of posting, both that and this tutorial are distributed using a CC-BY-NC-SA license.

Set Up Your Session

Installing the RWordPress and XMLRPC Packages

The RWordPress package is being distributed through GitHub. It can be installed using the install_github() operation in the devtools package. You also need to install Lang’s XMLRPC package as well.


Load Necessary Packages

In addition to RWordPress and XMLRP, we need knitr, a suite of operations for generating reports.


Create / Load a Script with Your Credentials

To post to WordPress, your login and password must be included in the script. Posting or circulating a Markdown file with your WordPress login credentials creates a huge web security risk. On the other hand, we teach you to be open about your coding, so that others can review, replicate, and build on it. How to negoatiate the two?

Bumgartner’s solution is to add the following variables to your .Rprofile file using this code

options(WordPressLogin = c(yourUserName = 'yourPassword'),
        WordPressURL = 'yourWordPressURL')

Do not delete the quotation marks in this template. For the ‘yourWordPressURL’, be sure to add a “https://” before and and “/xmlrpc.php” after your site address. So, for the site “joeblog.com”, you would enter “https://joeblog.com/xmlrpc.php”

Once you have generated and stored the file, you can add it to any Markdown file that you intend to post. I called my file “WPCrds.R”:

source("E:/My Documents/BlogCreds.R") 
#Or wherever you store the file

Set Images to Post to imgur.com

To save time and resources, post your images to the open online site Imgur.com. To do so, add these knitr options to your script:

# To upload images to imgur.com
opts_knit$set(upload.fun = imgur_upload, base.url = NULL)  

# Set default image dimensions
# Change them to change the dimensions of figures
opts_chunk$set(fig.width = 5, fig.height = 5, cache = TRUE)

Generate a Polished html Report

Create a Markdown file that renders your report in html. Render it locally to something sufficiently polished, and then move on to the next step.

I will download and insert an image into the report, in case someone needs to do that:

#Download the image
  destfile = "BBCard.jpg")

Then, OUTSIDE the chunk, enter into the main text of the document this line, without the hashtag

![Baseball Card](BBcard.jpg)

Baseball Card
Baseball Card

Post Your Information

In another chunk, set your post title as the variable postTitle, and define fileName as the name of the Markdown file that you are using to generate the post:

postTitle = "Your Title"
fileName = "Your-Markdown-File.Rmd"

Post using the knit2wp command, whose options include:

  • the Markdown file name (option: input)
  • the post title (option: title)
  • whether the post should be published upon rendering (option: publish, set true to directly publish – not advisable)
  • for a new post, the action variable should be set to “newPost” (option: action)
  • to set the post’s category. Use the slugs designated on your site. (option: categories)
  • to set the post’s tags. Use the slugs designated on your site. (option: tags)
postID <- knit2wp(
        input = fileName, 
        title = postTitle, 
        publish = FALSE,
        action = "newPost",
        categoories = c("Insert Slugs here"),
        tags = c("insert slugs here"),
        mt_excerpt = "Insert excerpt here"

Clean It Up on WordPress

From here, you will have a draft post on your WordPress site. I find WordPress to have a far more user-friendly interface to complete the last steps of a post.

Remember: Risk the temptation to do everything in R if it costs a lot of time. Yes, it would be cool if you could do it. The problem is no one but data nerds will appreciate it, and there’s not a lot of data nerds out there.


To post to WordPress through R Markdown, start with this setup to your script. Remember that the source() line points to a file with your credentials. For this post, it is:


postTitle = "Post to WordPress via R Markdown"
fileName = "Using-RWordPress.Rmd"

postID <- knit2wp(
        input = fileName, 
        title = postTitle, 
        publish = FALSE,
        action = "newPost",
        categories = c("analytics"),
        tags = c("communications", "Markdown"),
        mt_excerpt = "Publish a Markdown report direct to your WordPress blog"

Then write the script until it is polished, and then you can post by running this code. I recommend that you set eval = F, so that it doesn’t run when you render the Markdown file into html. Then, once the file runs, execute this code on its own, not as part of a larger operation.

Then, polish the piece in WordPress.

Getting Started with GitHub and RStudio

GitHub is an online code repository that is maintained by Microsoft. It is an excellent, free-to-use repository that allows you to save, update, and share scripts and output. It is useful for many things, including:

  • Version control, keep track of old versions of your scripts and track how you have updated them.
  • Code repository, a useful system for storing and disseminating code. It is an effective way to distribute programs or allow people to check your work.
  • Collaborative coding, upload your work on a collaboratively-coded script or download your colleagues’ recent work. Helps prevent a situation in which a team is working on different versions of a script

I’m sure that there are other great uses. If you want to share ideas with your colleagues, you can add them below in the comments section.

This tutorial is adapted from a tutorial from the University of Chicago. Readers should visit that site for a more detailed walk-through.

Start a Git Repository

On GitHub.com, create a “New Repository” (look for a green button). Click the green button to start an archive

Create a new repository. Make the repository public, and initialize it WITH a README file.

Create a Project Connected to the Repository

Click File > New Project > Version Control > Git

Click Version Control
Choose Git

You will then be asked for this information. In the bottom field, name the folder that will contain your new project folder. In the middle field, give your project a name. The top field requires the URL for this project’s associated Git.

Empty Info Box

You can get the address for your Github repostory by visitng the repository, clicking the green button, and getting the HTTPS clone address. Add that address to the top line.

Get Your Repository Address from Github

Complete the information to create the R Project file.

Filled Out Form

You have now created a project. It will remember the state of your RStudio session when you exit, and will bring it up again when you open the project again in the Project menu:

The Project Menu

Push Your Scripts or Script Changes to GitHub

Select the file you wish to upload, and click “commit”

Stage Your Script

Fill out the popup window. Write a comment and click “Commit”. Then “Push”

Et voila!, your script is posted to GitHub!

Pulling a Repository

Want to see if someone changed your repository while you were away? Press the “Pull” button in the Git window:

Click Pull to Download Changes

Labeling Exhibits in R Markdown

This tutorial describes how to label exhibits in your Markdown file. We will caption tables, figures, and images. This tutorial shows quick-and-dirty methods. Download the Markdown file used to generate this post here.


Imagine I want to convert this data frame named “table.raw” to a polished table in a report that I am generating using Markdown.

##            city  pop
## 1      New York 22.6
## 2   Los Angeles 18.7
## 3       Chicago  9.8
## 4          D.C.  9.8
## 5 San Francisco  9.6

Were I to generate the table using the kable() command from the knitr package, I could implement the caption using the command option caption. You can format the table using kableExtra package (click here for tips on formatting kable() tables). I will add the caption “Major Metro Area Populations”:

library(knitr)                                                     #Load packages
kable(table.raw,                                                   #Specify object presented in table
      col.names = c("City", "Pop."),                               #Setting column labels
      caption = "Table 1: Major Metro Area Populations") %>%       #Table caption inserted here,
                                                                   #Pipe at end of line to invoke next line:
  kable_styling(bootstrap_options = "striped", full_width = F)     #Additional formatting options
Table 1: Major Metro Area Populations
City Pop.
New York 22.6
Los Angeles 18.7
Chicago 9.8
D.C. 9.8
San Francisco 9.6


I use “table.raw” data to generate a figure using the package ggplot2. Note that I use the reorder() operation when defining the x-axis, in order to sort cities by population size rather than alphabetical order.:

To caption figures, you can set figure captions through the fig.cap option when you set your Markdown chunk.

``{r, echo = T, warning = F, fig.cap = "Major Metro Area Populations (in M)"}
ggplot(table.raw, aes(x = reorder(city, -pop), y = pop)) + geom_bar(stat = 'identity')

Figure 1: Major Metro Area Populations (in M)


Captioning images is easy for a basic image insertion. There are other methods, which allow for finer adjustments (e.g., click here).1. Note that you enter this command in the main body of a Markdown file, not in a chunk.

![Figure 2: Nice pic, even better caption!](Picture.jpg)

Figure 2: Nice pic, even better caption!

Need help with the Commons? Visit our
help page
Send us a message