web-dev-qa-db-ja.com

長いテキストを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

31
Eric Green

柔軟な方法でマークダウンテーブルを生成する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.        
------------------------------------------------------------------------------------
21
daroczig

素晴らしいpanderパッケージ以外の代替ソリューションは、kableExtracolumn_specを使用することです。この場合、次のコードでうまくいきます。

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