We R live!

After a small amount of faffing around, I am finally up and blogging. As I’m a big fan of R related content in blogs, I’ve been seeking an elegant way of incorporating R code and output into my blog posts . I’ve found my solution in Yihui Xie’s excellent knitr package, which you can read about here. I thought I’d make my first post a brief guide on this process.

The Function

The function you need is:

knit2wp()

But first, you’ll need to load some packages and change some options to allow you to post direct to WordPress.

install.packages('RWordPress', repos = 'http://www.omegahat.org/R', type = 'source') # installs the RWordPress package
install.packages('knitr', dependencies = TRUE) # installs the Knitr package from CRAN

Then load these packages as usual…

library(RWordPress)
library(knitr)

Next up, we need to set some options to allow R access to your blog, and to allow you to post graphics etc. Remember to change myUserName and myPassword to your WordPress login details. Your WordPress URL needs the suffix “xmlrpx.php” for this to work.

options(WordPressLogin = c(myUserName = "myPassword"), WordPressURL = "https://myblog.wordpress.com/xmlrpc.php")

Now we need to tell knitr to allow us to integrate graphics generated in R with our post. Do this using the option below:

opts_knit$set(upload.fun = function(file){library(RWordPress); uploadFile(file)$url;})

That’s it! Now we just need to write our post in standard Rmarkdown syntax and knitr will take care of the rest. When you’ve written your post, simply use the knit2wp() function to post to WordPress.

knit2wp("myBlogPost.Rmd", title = "A Blog Post Written in R", publish = T)

My blog posts from now on will be littered with R code and output, hopefully some of which you will find useful and/or interesting.
Thanks Yihui for this excellent package and function, and März for this excellent tutorial post which I found very helpful when learning how this works.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s