How can I split a table so that it appears side by side in R markdown?

一世执手 提交于 2020-02-25 09:36:07

问题


I'm writing a document with R markdown and I'd like to put a table. The problem is that this table only has two columns and takes a full page, which is not very beautiful. So my question is : is there a way to split this table in two and to place the two "sub-tables" side by side with only one caption ?

I use the kable command and I tried this solution (How to split kable over multiple columns?) but I could not do the cbind() command.

Here's my code to create the table :

---
title: 
author: 
date: "`r format(Sys.time(), '%d %B, %Y')`"
output: pdf_document
indent: true
header-includes:
  - \usepackage{indentfirst}
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```{r, echo = FALSE}
kable(aerop2, format = "markdown")

where aerop2 is my data frame with a list of country names in column 1 and the number of airports in each of these countries in column 2.

I have a long two-column table which is a waste of space. I would like to split this table in two sub-tables and put these sub-tables side by side with a caption that includes both of them.


回答1:


This doesn't give a lot of flexibility in spacing, but here's one way to do it. I'm using the mtcars dataset as an example because I don't have aerop2.

---
output: pdf_document
indent: true
header-includes:
  - \usepackage{indentfirst}
  - \usepackage{booktabs}
---

```{r setup, include=FALSE}
library(knitr)
opts_chunk$set(echo = TRUE)
```

The data are in Table \ref{tab:tables}, which will float to the top of the page.

```{r echo = FALSE}
rows <- seq_len(nrow(mtcars) %/% 2)
kable(list(mtcars[rows,1:2],  
           matrix(numeric(), nrow=0, ncol=1),
           mtcars[-rows, 1:2]), 
      caption = "This is the caption.",
      label = "tables", format = "latex", booktabs = TRUE) 
```

This gives:

Note that without that zero-row matrix, the two parts are closer together. To increase the spacing more, put extra copies of the zero-row matrix into the list.



来源:https://stackoverflow.com/questions/56445149/how-can-i-split-a-table-so-that-it-appears-side-by-side-in-r-markdown

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!