Somethime you like to document your R-code or your results optained by R. You might save all the plots and put them into a Word or Powerpoint document, or you love LaTeX and you put your plots into it. Imagin you now have to change some small thingy: you need to go through the whole process again: run the R script, save the plots and put them into your document, some output nubers / tables might have changed as well. And you need to go through your whole document again and check if you did not forget anything. This is where R Markdown developped by the R Studio company comes in handy. You can write your document using the markdown langage, add so called chunks for R code and knit it to a pdf, html or word file using knitr. The R code in these chunks can be displayd, their output can be shown and plots are displayed.
R markdown is easy to use and nicely integrated into the wide spread R editor: RStudio. To start check for example the following tutorial, or check this youtube movie.
A nice feature of markdown is the ability to create a table quite an easy way:
| | a | b | |----|---|---| |bla1| 1 | 2 | |bla2| 3 | 4 | |bla3| 5 | 6 |
resulting in:
a | b | |
---|---|---|
bla1 | 1 | 2 |
bla2 | 3 | 4 |
bla3 | 5 | 6 |
to display a dataframe in such a table the knitr::kable
command can be used (make sure you use the {r, results='asis'}
parameter to the chunk):
knitr::kable(data.frame(a = c(1,2,3), b = c(1,3,5)))
a | b |
---|---|
1 | 1 |
2 | 3 |
3 | 5 |
If you name the rows, the table shows these row names as well.
myDF <- data.frame(a = c(1,2,3), b = c(1,3,5))
rownames(myDF) <- c("a", "b", "c")
knitr::kable(myDF)
a | b | |
---|---|---|
a | 1 | 1 |
b | 2 | 3 |
c | 3 | 5 |
Which is much nicer than the output of plain R:
data.frame(a = c(1,2,3), b = c(1,3,5))
## a b ## 1 1 1 ## 2 2 3 ## 3 3 5
Same is true for matrices:
m <- matrix(c(1,2,3, 3, 7, 4), nrow = 2)
rownames(m) <- c("a", "b")
colnames(m) <- c("a", "b", "c")
knitr::kable(m)
a | b | c | |
---|---|---|---|
a | 1 | 3 | 7 |
b | 2 | 3 | 4 |
You might be interested in an R markdown cheatsheets (actually you might be interested in all RStudio’s cheatsheets ). Furthermore check the R markdown reference, as well as some Markdown tutorials:
And pages on Knitr:
You might be interested in Spin, which is usefull to create Reports using code from an R file, you do not longer have to duplicate code to make a markdown documentation, as you would using knitr.
There are other ways to present your R code and results: