2016-08-31 40 views
0

我想添加填充到我將在一個RMarkdown文件中創建的表中,該文件將生成PDF和HTML flexdashboard。我知道我可以使用許多函數/包(pander,xtable,DT等),但我更願意使用knitr包中的kable函數。不適用格式=「html」

我遇到的麻煩是填充參數似乎不工作。我將不勝感激任何幫助解決這個問題,而不必將自定義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) 

enter image description here

我使用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 
+0

我沒有在示例中看到與格式「html」組合使用的填充。但基於這篇文章http://stackoverflow.com/questions/17717323/align-two-data-frames-next-to-each-other-with-knitr你可以嘗試>科布(頭(汽車),格式=' html',table.attr ='cellpadding =「10」') –

+0

感謝您的建議。像Martin一樣,我無法使table.attr ='cellpadding =「10」'正常工作。 – MCDAngelo

回答

4

選項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> 

enter image description here


另一種選擇是使用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> 

這裏我添加類myTable到我想修改的表。之後我執行一些JavaScript(請參閱評論)。 (例如$('table.myTable td').css('background-color','red');

+0

我希望避免添加CSS或JavaScript,但似乎這是覆蓋默認表屬性的唯一方法。感謝這個例子! – MCDAngelo