Knitr - 居中对齐并分隔 table of tables

Knitr - Centre align and separate a table of tables

我正在使用 rmarkdown,我需要构建一个 table 的 2 table 以便

下面,我包括了两个 tables 和一些几乎到达那里的降价,但我们将不胜感激。 我认为 HTML 的最后一行(就在代码段的底部)是我需要帮助的地方。

数据和解决问题的方法

---
title: "A tale of two tables"
output: html_document
---
```{r global_options, R.options=knitr::opts_chunk$set(warning=FALSE, message=FALSE)}
```

```{r two-tables, results='asis'}
library(tidyverse)
library(knitr)
library(kableExtra)
library(formattable)

a <- tribble(~location, ~'Month (persons)', ~'TTY (persons)', ~'TTY % change',
       'new_south_wales',1604,40328,3.3,
       'victoria',-2118,13415,3.5,
       'queensland',214,10023,3.2,
       'south_australia',1969,11787,5.0,
       'western_australia',531,1316,1.6,
       'tasmania',-887,2428,1.9,
       'northern_territory',-44,570,2.4,
       'australian_capital_territory',32,-434,-3.1,
       'australia',78,1060,4.8)

b <- tribble(~series,~Dec,~Jan,~TTY,
       'FT employed', 12700, 49800, 293200,
       'PT employed', 20700, 65900, 110100,
       'Total', 33500, 16000, 403300,
       'per cent', 0.3, 0.1, 3.3,
       'Agg hours worked', -0.8, -1.5, 0.5,
       'Part rate', 65.7, 65.6, 64.6,
       'Ue', 5.56, 5.49, 5.7)

### Creating the tables
## Federal employment table
test_federal <- kable(b, format = "html", output = F) %>%
  kable_styling(c("striped", 'hover', 'condensed', 'responsive'), full_width = F, position = 'left', font_size = 11) %>%
  add_indent(4) %>% 
  row_spec(row = 3, bold = TRUE) %>% 
  add_header_above(c(" ", 'Month (sa)' = 2, 'Year (sa)' = 1))

## State employment table
test_state <- a %>% 
  mutate(
    'TTY % change' = color_bar('lightblue')(.$`TTY % change`)
  ) %>% 
  kable(format = "html", escape = FALSE, output = F) %>%
  kable_styling(c("striped", 'hover', 'condensed', 'responsive'), full_width = F, position = 'right', font_size = 11) %>% 
  row_spec(row = 9, bold = TRUE) %>% 
  add_header_above(c("", "Dec" = 1, "Dec" = 1, "Dec" = 1))

cat(c('<table><tr valign="top"><td>', test_federal, '</td>', '<td>', test_state, '</td></tr></table>'), sep = '')
```

要使 table 居中,您可以将 table margin 设置为 auto

为了将两个 table 分开,我看到了两个解决方案。

使用单元格填充

我认为这是最明显的解决方案。您可以将 padding 应用于您的单元格。例如:

cat(
  c('<table style="margin: auto"><tr valign="top"><td style="padding-right: 2cm">', 
    test_federal, 
    '</td>', 
    '<td>', 
    test_state, 
    '</td></tr></table>'
  ), 
  sep = ''
)

使用边框间距

您可以对 <table> 个元素使用 border-spacing property
为了使用 border-spacing,您必须将 border-collapse 属性 设置为 separate

将最后一行替换为:

cat(
  c('<table style="margin: auto; border-collapse: separate; border-spacing: 2cm"><tr valign="top"><td>', 
    test_federal, 
    '</td>', 
    '<td>', 
    test_state, 
    '</td></tr></table>'
  ), 
  sep = ''
)

与第一个解决方案的不同之处在于,您在第一个单元格之前和最后一个单元格之后得到一个 space。您可以看到删除 margin: auto.

的区别