Programmatically creating Markdown tables in R with KnitR

Solution 1:

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.

Solution 2:

Two packages that will do this are pander

library(devtools)
install_github('pander', 'Rapporter')

Or ascii

pander is a slightly different approach to report construction, (but can be useful for this feature).

ascii will allow you to print with type = 'pandoc (or various other markdown flavours)

library(ascii)
print(ascii(head(iris[,1:3])), type = 'pandoc')



    **Sepal.Length**   **Sepal.Width**   **Petal.Length**  
--- ------------------ ----------------- ------------------
1   5.10               3.50              1.40              
2   4.90               3.00              1.40              
3   4.70               3.20              1.30              
4   4.60               3.10              1.50              
5   5.00               3.60              1.40              
6   5.40               3.90              1.70              
--- ------------------ ----------------- ------------------

Note that in both these cases, it is directed towards using pandoc to convert from markdown to your desired document type, however using style='rmarkdown' will create tables that are compatible with this markdown package and inbuilt conversion in rstudio.