Use xtable to print html table in R markdown file

Psidom picture Psidom · May 26, 2016 · Viewed 10.5k times · Source

I would like to print a nicer table with a data frame in R mark down file, and I know how to use kable to print it, but I'd like a little bit more control options for which I am experimenting with the xtable package. However, I am really stuck with a silly problem which is that it doesn't print the table but html code in the file. So for example, if I want to print a default data set cars I would do:

```{r}
library(xtable)
print(xtable(head(cars)), type = "html")
```

which gives me this piece of html code.

## <!-- html table generated in R 3.2.5 by xtable 1.8-2 package -->
## <!-- Wed May 25 19:06:33 2016 -->
## <table border=1>
## <tr> <th>  </th> <th> speed </th> <th> dist </th>  </tr>
##   <tr> <td align="right"> 1 </td> <td align="right"> 4.00 </td> <td align="right"> 2.00 </td> </tr>
##   <tr> <td align="right"> 2 </td> <td align="right"> 4.00 </td> <td align="right"> 10.00 </td> </tr>
##   <tr> <td align="right"> 3 </td> <td align="right"> 7.00 </td> <td align="right"> 4.00 </td> </tr>
##   <tr> <td align="right"> 4 </td> <td align="right"> 7.00 </td> <td align="right"> 22.00 </td> </tr>
##   <tr> <td align="right"> 5 </td> <td align="right"> 8.00 </td> <td align="right"> 16.00 </td> </tr>
##   <tr> <td align="right"> 6 </td> <td align="right"> 9.00 </td> <td align="right"> 10.00 </td> </tr>
##    </table>

But I want an html table instead of the html code being displayed. Does anybody have any suggestions?

Answer

Edward R. Mazurek picture Edward R. Mazurek · May 26, 2016

Make sure to put 'asis' in quotes.

```{r, results='asis'}
library(xtable)
print(xtable(head(cars)), type = "html")
```

enter image description here