Align Multiple Tables Side By Side


Answer :

Just put two data frames in a list, e.g.

t1 <- head(mtcars)[1:3] t2 <- head(mtcars)[4:6] knitr::kable(list(t1, t2)) 

Note this requires knitr >= 1.13.


I used this Align two data.frames next to each other with knitr? which shows how to do it in html and this https://tex.stackexchange.com/questions/2832/how-can-i-have-two-tables-side-by-side to align 2 Latex tables next to each other. It seems that you cannot freely adjust the lines of the table as you can do it with xtable (does anybody know more about this?). With format = Latex you get a horizontal line after each row. But the documentation shows two examples for other formats. One using the longtable package (additional argument: longtable = TRUE) and the other using the booktabs package (booktabs = TRUE).

--- title: "sample" output: pdf_document header-includes: - \usepackage{booktabs} ---  ```{r global_options, R.options=knitr::opts_chunk$set(warning=FALSE, message=FALSE)} ```   ```{r sample, echo=FALSE, results='asis'} library(knitr) library(xtable)  t1 <- kable(head(mtcars)[1:3], format = "latex", booktabs = TRUE) t2 <- kable(head(mtcars)[4:6], format = "latex", booktabs = TRUE)  cat(c("\\begin{table}[!htb]     \\begin{minipage}{.5\\linewidth}       \\caption{}       \\centering",         t1,     "\\end{minipage}%     \\begin{minipage}{.5\\linewidth}       \\centering         \\caption{}",         t2,     "\\end{minipage}  \\end{table}" ))   ``` 

enter image description here


here a solution for html documents

(As this question was asked very broadly and not specifically referring to LaTeX).

Requires knitr and kableExtra

--- title: "Side by side" output: html_document ---   ```{r sample, echo=FALSE} library(knitr) library(kableExtra) t1 <- head(mtcars)[1:3] t2 <- head(mtcars)[4:6] ``` ## as list ```{r} kable(list(t1, t2)) ```  ## with float ```{r, echo = FALSE} kable(t1) %>%   kable_styling(full_width = FALSE, position = "float_left") kable(t2) %>%   kable_styling(full_width = FALSE, position = "left") ``` 

It is intentional that table t2 gets position = "left". If you allow it to float, this will not block the rest of the paragraph and mess up the following lines in your document.

result:

enter image description here


Comments

Popular posts from this blog

Are Regular VACUUM ANALYZE Still Recommended Under 9.1?

Can Feynman Diagrams Be Used To Represent Any Perturbation Theory?