Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrapping pandoc table column names in r markdown

I am creating a pandoc.table with long column name that I want to wrap so my table does not go off the pdf page. I know you can use split.tables, but that takes away the clarity of the table. Using split.cells doesn't seem to do anything, even when supplied as a vector.

---
  output : pdf_document
---

```{r,echo=FALSE, results="asis"}
library(pander)
mytab = data.frame(ReallySuperExtraLongColumnNameThatIWantToWrap=1:2, col2=2001:2002)
pandoc.table(mytab)
``` 
like image 243
Killian Avatar asked Mar 25 '16 14:03

Killian


1 Answers

The following will produce a table with a line break in the header:

```{r,echo=FALSE, results="asis"}
library(pander)
mytab = data.frame("ReallySuperExtraLongColumn\nNameThatIWantToWrap"=1:2,
                  col2=2001:2002,
                  check.names = FALSE)
pandoc.table(mytab)
``` 

The line break is encoded with \n. This is not an allowed character in a columnname, and the data.frame() function would normally remove it. You can use check.names = FALSE to suppress this behaviour and keep the column names exactly as you entered them. Alternatively, you could redefine the column name on a separate line:

mytab = data.frame(ReallySuperExtraLongColumnNameThatIWantToWrap=1:2, col2=2001:2002)
names(mytab)[1] = "ReallySuperExtraLongColumn\nNameThatIWantToWrap"

You can also set the width of the cells with split.cells. The line breaks will then be generated automatically, however, breaks only appear when there is a space in your column header. An example:

```{r,echo=FALSE, results="asis"}
library(pander)
mytab = data.frame("Really Super Extra Long Column Name That I Want To Wrap"=1:2,
                  col2=2001:2002,
                  check.names = FALSE)
pandoc.table(mytab, split.cells = 15)
``` 

This gives breaks after "Extra" and "Name". Note that you still need check.names = FALSE, because also spaces are not allowed in data frame names.

like image 192
Stibu Avatar answered Sep 25 '22 23:09

Stibu