5

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)
``` 
MichaelChirico
  • 33,841
  • 14
  • 113
  • 198
Killian
  • 89
  • 2
  • 10

1 Answers1

6

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.

Stibu
  • 15,166
  • 6
  • 57
  • 71
  • Thanks for the tips! I realized that changing the "style" of the pandoc table will actually do what I want as well! I was using style = 'rmarkdown'; however, style = 'multiline' takes care of it! – Killian Mar 25 '16 at 17:57
  • But `style = "multiline"` is the default, so if you don't specify `style`, this will be used. It's true that `style = "rmarkdown"` seems not to support line breaks in cells, but setting `style = "multiline"` allone does not add line breaks where there are no spaces. It will break at spaces and use `split.cells = 30` by default. – Stibu Mar 25 '16 at 18:30
  • 1
    This answer did not work for me. I needed to use the argument `keep.line.breaks` to honor `\n`. – jsta Feb 01 '17 at 14:29