Blog posts with rmarkdown on Jekyll with servr and knitr
So I’m trying to set up my jekyll system to allow me to edit rmarkdown files and insert them into the jekyll system.
This is one way, but I couldn’t get this to work (too impatient), and in the end I found this post with a neat script which I have edited. My edits are mainly to fix the issue that my jekyll instance runs in a /blog/ subdirectory, and also to allow rebuilding of a page by removing the previously generated ../fig/xxx directory from a previous run of the script. I’m sure that there will be easier ways to accomplish this (without the hard coding of the /blog) but I’m too much of a novice with jekyll.
#!/usr/bin/env Rscript
input <- commandArgs(trailingOnly = TRUE)
#KnitPost <- function(input, base.url = "/") {
KnitPost <- function(input, base.url = "/blog/") {
require(knitr)
opts_knit$set(base.url = base.url)
# fig.path <- paste0("../figs/", sub(".Rmd$", "", basename(input)), "/")
fig.path <- paste0("figs/", sub(".Rmd$", "", basename(input)), "/")
opts_chunk$set(fig.path = fig.path)
opts_chunk$set(fig.cap = "center")
render_jekyll()
print(paste0("../_posts/", sub(".Rmd$", "", basename(input)), ".mkd"))
knit(input, output = paste0("../_posts/", sub(".Rmd$", "", basename(input)), ".mkd"), envir = parent.frame())
# now move the fig file
# 1 but remove existing directory first
rm.command<-paste0("rm -r ","../figs/", sub(".Rmd$", "", basename(input)), "/")
# 2 - create a system command to move from the subdir to the parent directory,
mv.command<-paste0("mv ","figs/", sub(".Rmd$", "", basename(input)), "/", " ../figs/")
# 3 - now run it
system(rm.command)
system(mv.command)
}
KnitPost(input)
So let’s try some R…
R code chunks
Following is from here
Now we write some R code chunks in this post. For example,
mpg | cyl | disp | hp | drat | wt | qsec | vs | am | gear | carb | |
---|---|---|---|---|---|---|---|---|---|---|---|
Mazda RX4 | 21.0 | 6 | 160 | 110 | 3.90 | 2.62 | 16.5 | 0 | 1 | 4 | 4 |
Mazda RX4 Wag | 21.0 | 6 | 160 | 110 | 3.90 | 2.88 | 17.0 | 0 | 1 | 4 | 4 |
Datsun 710 | 22.8 | 4 | 108 | 93 | 3.85 | 2.32 | 18.6 | 1 | 1 | 4 | 1 |
Hornet 4 Drive | 21.4 | 6 | 258 | 110 | 3.08 | 3.21 | 19.4 | 1 | 0 | 3 | 1 |
Hornet Sportabout | 18.7 | 8 | 360 | 175 | 3.15 | 3.44 | 17.0 | 0 | 0 | 3 | 2 |
Valiant | 18.1 | 6 | 225 | 105 | 2.76 | 3.46 | 20.2 | 1 | 0 | 3 | 1 |
Just to test inline R expressions1 in knitr, we know the first element in x
(created in the code chunk above) is 9.44. You can certainly draw some graphs as well:
Other ways to do this
* http://rmarkdown.rstudio.com/rmarkdown_websites.html
-
The syntax in R Markdown for inline expressions is
`r code`
, wherecode
is the R expression that you want to evaluate, e.g.x[1]
. ↩
Leave a Comment