Programmatically creating Markdown tables in R with KnitR

TARehman picture TARehman · Mar 18, 2013 · Viewed 72.5k times · Source

I am just starting to learn about KnitR and the use of Markdown in generating R documents and reports. This looks to be perfect for a lot of the day to day reporting that I have to do with my job. However, one thing that I'm not seeing is an easy way to print data frames and tables using Markdown formatting (sort of like xtable, but with Markdown instead of LaTeX or HTML). I know that I can just embed the HTML output from xtable, but I was wondering if there were any Markdown-based solutions?

Answer

Artem Klevtsov picture Artem Klevtsov · Nov 8, 2013

Now knitr (since version 1.3) package include the kable function for a creation tables:

> library(knitr)
> kable(head(iris[,1:3]), format = "markdown")
|  Sepal.Length|  Sepal.Width|  Petal.Length|
|-------------:|------------:|-------------:|
|           5,1|          3,5|           1,4|
|           4,9|          3,0|           1,4|
|           4,7|          3,2|           1,3|
|           4,6|          3,1|           1,5|
|           5,0|          3,6|           1,4|
|           5,4|          3,9|           1,7|

UPDATED: if you get raw markdown in a document try setup results = "asis" chunk option.