将长文本包装在 kable table 列中

wrap long text in kable table column

我想在我的电缆中包裹长文本 table。这是一个 table 的简单示例,其列文本太长,需要换行以使 table 适合页面。

---
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)
```

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

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

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