2015-04-03 35 views
13

我想在我的kable表格中包裝長文本。以下是列表文本的一個簡單示例,其中列文本太長,需要將表格打包以適合頁面。在kable表格列中包裝長文本

--- 
title: "test" 
output: pdf_document 
--- 

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


This is my test 

```{r test, echo=FALSE} 
test <- data.frame(v1=c("This is a long string. This is a long string. This is a long string. This is a long string. This is a long string.", 
         "This is a another long string. This is a another long string. This is a another long string. This is a another long string. This is a another long string."), 
        v2=c(1, 2)) 
kable(test) 
``` 

enter image description here

回答

12

我創建了pander包產生以靈活的方式降價表。默認情況下,它將用長字符串拆分單元格爲30個字符,但有一堆global options和fn參數可以覆蓋它們,啓用連字符和其他調整。快速演示:

> pander::pander(test) 

----------------------------------- 
       v1    v2 
------------------------------ ---- 
This is a long string. This is 1 
a long string. This is a long  
string. This is a long string.  
    This is a long string.   

This is a another long string. 2 
This is a another long string.  
This is a another long string.  
This is a another long string.  
This is a another long string.  
----------------------------------- 

> pander::pander(test, split.cell = 80, split.table = Inf) 

------------------------------------------------------------------------------------ 
             v1           v2 
------------------------------------------------------------------------------- ---- 
This is a long string. This is a long string. This is a long string. This is a 1 
         long string. This is a long string.       

This is a another long string. This is a another long string. This is a another 2 
    long string. This is a another long string. This is a another long string.   
------------------------------------------------------------------------------------ 
+1

看起來很漂亮,@達羅齊格。有沒有列名稱的參數?對不起,如果我錯過了。 – 2015-04-03 04:11:15

+1

謝謝@EricGreen。你錯過了什麼名字?可能你最好將它們設置在'data.frame'級別。 – daroczig 2015-04-03 04:15:32

+0

'kable'有'col.names'來重新定義「我的文本」 – 2015-04-03 04:16:48

7

的替代比真棒pander包中的其它的解決方案是在kableExtra使用column_spec。在這種情況下,下面的代碼可以做到這一點。

kable(test, "latex") %>% 
    column_spec(1, width = "10em")