【问题标题】:wrap long text in kable table column在 kable 表列中换行长文本
【发布时间】:2015-06-08 03:34:13
【问题描述】:

我想在我的 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)
```

【问题讨论】:

    标签: r knitr


    【解决方案1】:

    除了很棒的pander 包之外,另一种解决方案是在kableExtra 中使用column_spec。在这种情况下,下面的代码可以解决问题。

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

    【讨论】:

    • 如果您的表格浮动在页面之外,kableExtra 包中的kable_styling(full_width = TRUE) 也会在需要时引入文本换行。
    【解决方案2】:

    我创建了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.        
    ------------------------------------------------------------------------------------
    

    【讨论】:

    • 看起来很漂亮,@daroczig。列名有参数吗?对不起,如果我错过了。
    • 谢谢@EricGreen。你想念什么关于 colnames 的论点?可能你最好将它们设置在data.frame 级别。
    • kablecol.names 将“v1”重新定义为“我的文本”
    • 对于我当前的用例,在 data.frame 级别设置效果很好。我不确定我是否总是想这样做,但在这种情况下很好。 pander 上的出色工作
    • 感谢@EricGreen 的反馈。老实说,在pander 中我从来没有真正需要这样的新参数,我总是在传递给pander 之前调整实际的data.frame 以满足我的需要,但如果你能描述一个好的用例,然后请在 GH 上打开一个问题。
    猜你喜欢
    • 2022-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    相关资源
    最近更新 更多