Simple manual RMarkdown tables that look good in HTML, PDF and DOCX

Inspired by daroczig’s comments, especially the clue that pander translates to pandoc’s pipe syntax, I took a closer look at the pander documentation and found reference to cat. After some experimentation, I found the winner:

```{r table2, echo=FALSE, message=FALSE, warnings=FALSE, results='asis'}
tabl <- "  # simple table creation here
| Tables        | Are           | Cool  |
|---------------|:-------------:|------:|
| col 3 is      | right-aligned | $1600 |
| col 2 is      | centered      |   $12 |
| zebra stripes | are neat      |    $1 |
"
cat(tabl) # output the table in a format good for HTML/PDF/docx conversion
```

This produces uniformly good looking tables in HTML, PDF and docx in my tests. Now I’m off to upvote daroczig on some other questions to thank him for getting me to the solution.

If you need a caption for your table… then you’ll need to do it a bit differently. Note that the caption will only be visible in the PDF, not in the HTML:

```{r table-simple, echo=FALSE, message=FALSE, warnings=FALSE, results='asis'}
require(pander)
panderOptions('table.split.table', Inf)
set.caption("My great data")
my.data <- " # replace the text below with your table data
  Tables        | Are           | Cool
  col 3 is      | right-aligned | $1600 
  col 2 is      | centered      |   $12 
  zebra stripes | are neat      |    $1"
df <- read.delim(textConnection(my.data),header=FALSE,sep="|",strip.white=TRUE,stringsAsFactors=FALSE)
names(df) <- unname(as.list(df[1,])) # put headers on
df <- df[-1,] # remove first row
row.names(df)<-NULL
pander(df, style = 'rmarkdown')
```

Leave a Comment