r knit kable 填充不适用于 format = "html"

MCD*_*elo 1 html r knitr r-markdown

我正在尝试向我在 RMarkdown 文件中创建的表格添加填充,该文件将生成 pdf 和 html flexdashboard。我知道我可以使用许多函数/包(pander、xtable、DT 等),但我更喜欢使用 knit 包中的 kable 函数。

我遇到的问题是填充参数似乎不起作用。如果您能帮助我解决这个问题,而无需将自定义 CSS 添加到我的文档中,我将不胜感激。

例如,我尝试将填充设置为 0、10、20 来运行代码,但 html 文件中的表格看起来都相同。

knitr::kable(head(cars), format = "html", padding = 0)
knitr::kable(head(cars), format = "html", padding = 10)
knitr::kable(head(cars), format = "html", padding = 20)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

我使用的是knitr_1.14和rmarkdown_1.0,我的会话信息如下。

R version 3.3.0 (2016-05-03)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1
Run Code Online (Sandbox Code Playgroud)

Mar*_*zer 5

该选项table.attr='cellpadding="20px"'对我不起作用。使用 CSS 样式并向表添加一个类会导致table.attr='class="myTable"'所有表都具有所需的填充属性(即使只有一个表带有新类)。

如果我只想修改一个表,我通常会使用 jQuery:

---
title: "Table Cell Padding"
output: html_document
---

```{r}
knitr::kable(head(cars), format = "html")
```
```{r}
knitr::kable(head(cars), format = "html", table.attr='class="myTable"')
```
<style>
  .myTable td {
    padding: 40px;
  }
</style>
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


另一种选择是使用 jQuery 编辑单个元素。以下示例以与上面的 CSS 样式相同的方式修改表格。

<script type="text/javascript">
  // When the document is fully loaded...
  $(document).ready(function() {
    // ... select the cells of the table that has the class 'myTable'
    // and add the attribute 'padding' with value '20px' to each cell
    $('table.myTable td').css('padding','20px');
  });
</script>
Run Code Online (Sandbox Code Playgroud)

这里我将类添加myTable到我要修改的表中。然后我执行一些 JavaScript(见评论)。$('table.myTable').css(...)您可以以相同的方式将任何其他 CSS 属性添加到表元素(或表本身)(例如$('table.myTable td').css('background-color','red');