- I'm trying to build tables in knitr using xtable.
- Some tables have multilevel column names
- I'm building the tables in functions and storing the output of the functions as variables
- these table variables are then used to build a knitr report
Code for the Rmd below
---
output:
pdf_document
---
```{r setup}
library(knitr)
library(xtable)
library(tidyverse)
data <- diamonds %>% head(3) %>% select(carat, cut, color, depth)
make_table <- function(){
addtorow_comp <- list()
addtorow_comp$pos <- list(0,0)
addtorow_comp$command <- c("\\multicolumn{3}{c}{all the Cs} & D \\\\\n",
"carat & cut & color & depth \\\\\n")
tmp <- xtable(data,
caption="a table",
align = c('l|','c{0.3in}', 'c{0.4in}','c{0.4in}|', 'c{0.4in}|'),
digits= c(0,0,0,0,1))
return(print(tmp, add.to.row = addtorow_comp,
include.colnames = FALSE,
rotate.colnames = FALSE,
include.rownames = FALSE,
type="latex"))
}
tbl_to_output <- make_table()
```
```{r output_table, results="asis", cache=FALSE}
tbl_to_output
```
tbl_to_output outputs the latex with the text including escape characters, e.g. \\ for a single slash and \n for newline. If I were to run the print command directly from the the output_table chunk it works fine, but I want to separate the building of tables from where they display.


I add some corrections and comments, now it works:
An addition:
You can do it also by this way: