Quinten
Quinten

Reputation: 41523

Convert dataframe to markdown table in Quarto

I would like to convert a dataframe to a markdown table to use in html Quarto. We could use the simplermarkdown package with md_table to convert a dataframe to a markdown table. But the problem is that the output of the markdown is not converted to a html table. You can do this by copying the output and put it in the document, this is of course not automatically. Here is some reproducible code:

--- 
title: "example"
format: html
---

```{r}
library(simplermarkdown)
md_table(head(iris))
```

This is copied from output above:

|Sepal.Length|Sepal.Width|Petal.Length|Petal.Width|Species|
|------------|-----------|------------|-----------|-------|
|5.1         |3.5        |1.4         |0.2        |setosa |
|4.9         |3.0        |1.4         |0.2        |setosa |
|4.7         |3.2        |1.3         |0.2        |setosa |
|4.6         |3.1        |1.5         |0.2        |setosa |
|5.0         |3.6        |1.4         |0.2        |setosa |
|5.4         |3.9        |1.7         |0.4        |setosa |

Output:

enter image description here

As you can see, the output of the function does return the markdown format but doesn't automatically convert it to the desired output (like the copied code). So I was wondering if anyone knows how to automatically convert a dataframe to a markdown table in quarto?

Upvotes: 7

Views: 4357

Answers (2)

user12256545
user12256545

Reputation: 3022

Why going the extra way to cat the generated md table and output asis to generate html, if you are using knitr engine anyways? knitrhas a function kablefor tableling dataframes to markdown, html, and pdf. so we can directly convert the dataframe to an html table, without using intermediate markdown.

knitr::kable(head(iris),format = "html") # output format specification is optional

enter image description here

Upvotes: 6

Shafee
Shafee

Reputation: 20047

Try with output: asis and cat.

--- 
title: "example"
format: html
---

```{r}
#| output: asis
library(simplermarkdown)
cat(md_table(head(iris)))
```

markdown table converted from dataframe using simplermarkdown pkg

Upvotes: 3

Related Questions