Simple Markdown syntax for formatting your R scripts into WEB pages using knitr::spin()

Agustin.Lobo@ictja.csic.es

Most basic rules

# As for any R script, use # at the begining of the line to make an R commented line (as we do here)
# and write your R code normally (with no #), including graphic commands. 
# The R output will be preceeded by ## in the web page. For example:
x <- seq(-pi,pi,by=0.1)
x[1:10]
##  [1] -3.141593 -3.041593 -2.941593 -2.841593 -2.741593 -2.641593 -2.541593
##  [8] -2.441593 -2.341593 -2.241593
plot(x,sin(seq(-pi,pi,by=0.1)),type="l",col="red",xlab="angle",ylab="sin(x)",main="Example of graphic")

plot of chunk unnamed-chunk-1

Use lines starting by #’ to write all your “non R stuff” (as we do in this line)

To make headings, use #‘# Heading , as we did in line “Most basic rules” (add more # for subheadings, i.e: #’ ## Subheading)

To make lists, write lines such as #’ * item

Use lines starting by #+ to set markdown chunk options (once you know what they are)

Run your R script with require(knitr); spin(“scriptname.R”)

You will get 3 files: “scriptname.Rmd”, “scriptname.md” and “scriptname.html”. Open “scriptname.md” in RStudio and click on “Preview HTML”

Practice Now

Edit any of your R scripts with the above rules and visualize the resulting html. Get familiar with these few rules before going for the rest of this material. For example, now that you know how to make lists, make a simple script with the “Most basic rules” in list format. In the tutorial I try not to use any formatting that has not been explained before.

A bit more of style

Title

Write the text in a line begining by #‘and then put few “===” in the next #’ line as if you were underlining. See the title of this script as example ## More on Lists You can use: #‘* Item or #’ + Item

to make lists such as: * Item 1 * Item 2 * Item 3

For sub-items, just indent: * Item 1 * Subitem 1.1 * Subitem 1.2 * Item 2

If you want a number for each item, just use a number with . instead of * or +:

  1. Item 1
  2. Item 2
  3. Subitem 2.1
  4. Subitem 2.2

Note: have not been able to find a good way of geting the “2.1” style for the subitems

Important: Leave an empty #‘line or at least one (commented or not) line of R code after the list for the next #’ command to take effect

Special text

Comments

# you can write comments between /* and */ like C comments (the preceding #
# is optional)

Text formats

Copied from #’ [Markdown Cheatsheet] (https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet)

# Emphasis, aka italics, with *asterisks* or _underscores_.

asterisks or underscores

# Strong emphasis, aka bold, with **asterisks** or __underscores__.

asterisks or underscores

# Combined emphasis with **asterisks and _underscores_**.

asterisks and underscores

# Strikethrough uses two tildes. ~~Scratch this.~~

Scratch this.

# Litteral ("verbatim") text can be included within backticks: `$liter@lly#`

$liter@lly#

Wider text lines for R code and R output

Set:

w <- 80
options(width=180)
# when you are done, go back to previous width:
options(width=w)

Line breaks

lines in your R script will not match lines in the html. You need to include a soft line break to enforce a new line. You can accomplish this by inserting two spaces after each new line. See markdown tutorial L7

[According to Yihui] (https://groups.google.com/forum/#!topic/knitr/wyqwR1Uc29Q): In HTML,

# <br/> (without the #)

means a line break. You can use it in markdown as well. A more natural solution is to use the ‘hard_wrap’ option when converting markdown to HTML using the markdown package. See:

# ?markdown::markdownToHTML

Example: The following text:

# #' Hard line breaks in HTML are often ugly.<br/>  It is rare that you really need them. <br/> If you are looking for a way to control the width of the page/paragraph, <br/> CSS is the right solution.
# will become:

Hard line breaks in HTML are often ugly.
It is rare that you really need them.
If you are looking for a way to control the width of the page/paragraph,
CSS is the right solution.

# (You can also use double space instead of the <br/>)

Images (not resulting from R code)

Include inages that do not result from the R code you are documenting just as a link, but with ! before the []:
![Figure 1](Path_or_url/filename.bmp)
See markdown tutorial L4

Tables

simplest: just make width wider:

w <- 80
options(width=180)
tabla <- table(1:length(letters),letters)
print(tabla)
##     letters
##      a b c d e f g h i j k l m n o p q r s t u v w x y z
##   1  1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
##   2  0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
##   3  0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
##   4  0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
##   5  0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
##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 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0
##   25 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0
##   26 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
options(width=w)

xtable:

Reference: [Custom CSS for HTML generated using RStudio] (http://nsaunders.wordpress.com/2012/08/27/custom-css-for-html-generated-using-rstudio/)

data(iris)
require(xtable)
options(width=180)
# Note: must insert a line #+results='asis' (with no preceeding #') as a chunk option (explained below):
print(xtable(head(iris, 10)), type = 'html', include.rownames = F)
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
5.10 3.50 1.40 0.20 setosa
4.90 3.00 1.40 0.20 setosa
4.70 3.20 1.30 0.20 setosa
4.60 3.10 1.50 0.20 setosa
5.00 3.60 1.40 0.20 setosa
5.40 3.90 1.70 0.40 setosa
4.60 3.40 1.40 0.30 setosa
5.00 3.40 1.50 0.20 setosa
4.40 2.90 1.40 0.20 setosa
4.90 3.10 1.50 0.10 setosa

The conversion to html is made according to a *.css file (style file). The default provided by RStudion is in

Table style can be modified by using a customized style file (i.e. custom.css; see at the end)

More “advanced” tricks:

Options

Global options

Options can be set at the begining to hold for the entire script, although they will be eventually overriden by chunk options (see next section). An initial line of R code (thus with no “‘) such as
knitr::opts_chunk$set(results='hide')
will make that all the output from R code chunks will not be displayed in the final document.
The following
`knitr::opts_chunk$set(fig.width=12, fig.height=8, fig.path=’Figs/’, echo=FALSE, warning=FALSE, message=FALSE)’
will set the size and path of figures, avoid writing R code, warning and informational messages to the final document.

Chunk options

Chunk options control the behaviour of the chunks of R code and are written as lines starting by #+ (not #’#+ ) just before the actual R code

Control size of R figures

R figures are by default 7’‘x 7’’
Change these values for the next chunk with:
#+ fig.height=15, fig.width=9

Make selected chunks of R code become non-executable

Make the selected chunk being never executed

Use this chunk option in a new line before a computing-intensive chunk: #+ eval=FALSE
(Remember: chunk options start by #+ ,not by #’#+) * Example: not using #+ eval=FALSE:

3+2
## [1] 5
  • Example: using #+ eval=FALSE:
3+2

Make the selected chunk being executed the first time only (“using cache”)

Use this chunk option in a new line before a computing-intensive chunk: #+ chunkname, cache=TRUE
(chunkname is optional)
#‘(Remember: chunk options start by #+ ,not by #’#+) You will see the time in the html remaining constant after the first run of spin(“miknitr-spin.R”):

a1 <- date()
a1
## [1] "Wed Nov 18 12:56:43 2015"

If you set: #+ chunkname, cache=FALSE

the R code is executed at every run of spin(“miknitr-spin.R”) and the a2 value is thus updated in the html:

a2 <- date()
a2
## [1] "Wed Nov 18 13:46:16 2015"

Excerpt of Message by Yihui: If some code chunks are very time-consuming, you can consider caching or the old plain save()/load() method.

Style notes:

  • If you have non-executable chunks, note it at the begining of the script.
  • A convenient way to actually control the execution of the computing-intensive chunks, is using a variable:

#+ chunkcache2, cache=cacheoption

Instead of using TRUE/FALSE. Then at the very begining of the script you set:

cacheoption=TRUE
#or
cacheoption=FALSE

to control wether you want to skip or re-run the computing-intensive chunks.

Avoid unwanted messages

As adviced in this post

Some functions output information messages that become a problem within a loop, i.e:

require(lmodel2)
for (i in 1:3){
  delme <- lmodel2(runif(10)~rnorm(10))
}
## RMA was not requested: it will not be computed.
## 
## No permutation test will be performed
## RMA was not requested: it will not be computed.
## 
## No permutation test will be performed
## RMA was not requested: it will not be computed.
## 
## No permutation test will be performed

Use chunk option:

#+ chunkmessage, message=FALSE

to make it silent:

require(lmodel2)
for (i in 1:3){
  delme <- lmodel2(runif(10)~rnorm(10))
}

Comprehensive list of chunk options

Chunk options and package options

formatR: control line width of R commands and comments

In order to a long R command or comment in one single line, use package formatR

require(formatR)
tidy.source(text="1+2+3+4+5+6+7+8+9+1+2+3+4+5+6+7+8+91+2+3+4+5+6+7+8+9+1+2+3+4",width.cutoff=90)
## 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 91 + 2 + 3 + 4 + 5 + 6 + 
##     7 + 8 + 9 + 1 + 2 + 3 + 4

TOC

Once spin() has created the Rmd file, you can get an automatic TOC in the resulting html with:
(note we use the chunk option #+ eval=FALSE in this script to avoid executing the command)
(You normally execute this command outside the script)

knit2html('foo.Rmd', options = c('toc', markdown::markdownHTMLOptions(TRUE)))

See (https://groups.google.com/forum/#!topic/knitr/ljLsLRB4-Ic) (Note the “Issues still to be solved” at the end)

Run with a style defined by a custom.css

Based on * [Custom CSS for HTML generated using RStudio] (http://nsaunders.wordpress.com/2012/08/27/custom-css-for-html-generated-using-rstudio/) * vignette.css

A custom.css can be applied with markdownToHTML() after runing spin(“scriptname.R”) to enforce a given style:

# markdownToHTML("scriptname.md","scriptname.html",stylesheet="custom.css"))

Both the css and the TOC can be included in knit2html() once the Rmd file is generated.
Assuming the custom.css file is in path “/media/alobo/Iomega_HDD/Rutils/custom.css”, the final run would be:
(note we use the chunk option #+ eval=FALSE in this script to avoid executing the comands)
(You normally execute these commands outside the script)

require(markdown)
require (knitr) 
spin ("myscript.R")
knit2html('myscript.Rmd', options = c('toc', markdown::markdownHTMLOptions(TRUE)),stylesheet='/media/alobo/Iomega_HDD/Rutils/custom.css')

or, in case you do not want the TOC,

`knit2html('myscript.Rmd' ,stylesheet='/media/alobo/Iomega_HDD/Rutils/custom.css')`
## Error in eval(expr, envir, enclos): object 'knit2html('myscript.Rmd' ,stylesheet='/media/alobo/Iomega_HDD/Rutils/custom.css')' not found

Publish to RPubs

Please do not simply test these commands, use them when you have something relevant to contribute only ### Using RStudio Edit the resulting .Rmd or md file in RStudio, press the KnitHTML button and then the Publish button.
In this case, you will not be using your custom.css to convert the *.Rmd to html

Using a markdown command in the console

Use rpubsUpload() in the markdown R package. In this case you upload the html generated by spin(), thus including the style defined by an eventual custom.css file

Issues still to be solved