5

Within rmarkdown (in RStudio) I use htmlTable package to generate nice looking tables in my html documents. Now I want the same result when rendering a pdf document. The tables aren't rendered properly. How can I let rmarkdown generate tables in my pdf document the same way it does in my html's?

This is a working example of a .Rmd file with a table:

---
title: "test"
output: pdf_document
---

```{r results="asis"}
library(htmlTable)
c1 <- c("test1","test1","test2","test2")
c2 <- c(1,2,3,4)
data_object <- as.data.frame(cbind(c1,c2))
names(data_object) <- c("test","test2")
print(htmlTable(data_object))
```

Click knit pdf in RStudio.

The result in my pdf-document is:

test
library(htmlTable)
c1 <- c("test1","test1","test2","test2")
c2 <- c(1,2,3,4)
data_object <- as.data.frame(cbind(c1,c2))
names(data_object) <- c("test","test2")
print(htmlTable(data_object))
test
test2
1
1
1
2
1
2
3
2
3
4
2
4
1

The result (of the table part) should be:

enter image description here

Does anyone have an idea about how to solve this?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
rdatasculptor
  • 8,112
  • 14
  • 56
  • 81
  • related: https://stackoverflow.com/questions/63053465/how-to-convert-an-html-sjtable-from-the-sjplot-package-to-latex – tjebo Mar 12 '21 at 15:24

2 Answers2

5

If you want PDF output, you should transform the R object to

  • LaTeX or
  • markdown

The prior has a lot more formatting options, but the latter is a lot simpler and can be converted further to either HTML or PDF (besides a bunch of other formats). So instead of the htmlTable package, you might want to give a try to kable or the more robust pander package:

---
title: "test"
output: pdf_document
---

```{r}
library(pander)
data_object <- data.frame(test = paste0('test', 1:4), test2 = 1:4)
pander(data_object)
```

Resulting in the following PDF after calling rmarkdown::render on the above document:

enter image description here

daroczig
  • 28,004
  • 7
  • 90
  • 124
  • 1
    Thanks for the answer. I will try pander, though it's not an answer to my specific answer. Ar you sure there is no ways to change my html to markdown before rendering pdf? – rdatasculptor Oct 17 '15 at 07:07
  • Sure there is: you can use eg `pandoc` (the very same document converter used by RStudio/rmarkdown/pander to generate the HTML/PDF files from markdown) to transform the HTML to PDF: http://pandoc.org/README.html -- but it is used to be used on the HTML file not code chunks. – daroczig Oct 17 '15 at 16:30
1

I had the same issue with the sjPlot::tab_model() html tables and ended up creating a couple functions to help out.

Please see the Github repo https://github.com/gorkang/html2latex/.

In the repo you can find an example.Rmd file with step-by-step instructions. It works in a Ubuntu 20.04 system.

Gorka
  • 3,555
  • 1
  • 31
  • 37