r - 如何使用 R Markdown 和 Knitr 对齐 HTML 输出中的表格

标签 r knitr kable kableextra

我正在 RStudio 中试验 Knitr/KableExtra,但无法让我的表格使用 Web 浏览器的整个宽度或控制表格在屏幕上的对齐方式。

下面是代码示例,根据 kable_styling 文档,我尝试强制表格与屏幕左侧对齐,但在 html 输出中,表格始终居中。它看到左侧有一个我无法使用的无形边距。当我有一个包含更多字段的表格时,问题就出现了......左边的大边距仍然存在,迫使表格延伸到屏幕右侧并生成水平滚动条 - 非常烦人和丑陋。

有什么方法可以使用左边距的空间或强制表格真正向左对齐吗?

这是问题的一个例子:

example

---
title: "Untitled"
author: "ME"
date: "2/4/2020"
output: html_document
---

```{r setup, include=FALSE}
library(kableExtra)

knitr::opts_chunk$set(echo = TRUE)
```

## R Markdown

This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.

When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:

```{r cars}
x_html <- knitr::kable(head(mtcars), "html")
kable_styling(x_html, "striped", position = "left", font_size = 7)
```

最佳答案

您需要调整默认的 CSS 主题。例如,要使内容显示在可用宽度的 100% 上:


```{css}
.main-container {
    max-width: 100%;
}
```

还有其他解决方案,但这个可能是最简单的:


---
title: "Untitled"
author: "ME"
date: "2/4/2020"
output: html_document
---

```{r setup, include=FALSE}
library(kableExtra)

knitr::opts_chunk$set(echo = TRUE)
```

```{css}
.main-container {
    max-width: 100%;
}
```

## R Markdown

This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.

When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:

```{r cars}
x_html <- knitr::kable(head(mtcars), "html")
kable_styling(x_html, "striped", position = "left", font_size = 7)
```

关于r - 如何使用 R Markdown 和 Knitr 对齐 HTML 输出中的表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60065767/

相关文章:

r - if-else 条件取决于先前的值

r - knitr 缠结的 R 代码中缺少 block 名称

r - 在 xtable 中的多行上按组拆分标题

html - Kable、Flextable、Huxtable 到 HTML : force the display of cell contents on a single line

r - 列表中每个元素的 Knitr/kable 标题

r - 在 R 中添加具有增量的新列

r - 在数据表 (R) 中每三位数字添加逗号

r - R 中的模式按组

r - 如何在 markdown (.Rmd) 中包装代码和输出

在 kable 中用希腊字母重命名表的列名