Use hooks to format table in output

Lacking a better solution I’m currently re-parsing the character string representation that I receive in the hook. I’m posting it here since it kind of works. However, parsing a data frame’s string representation is never perfect. I haven’t tried the following with anything but my own data and I fully expect it to break on some common use-cases.

reparse <- function (data, comment, ...) {
    # Remove leading comments
    data <- gsub(sprintf('(^|\n)%s ', comment), '\\1', data)
    # Read into data frame
    read.table(text = data, header = TRUE, ...)
}

default_output_hook <- knit_hooks$get('output')

knit_hooks$set(output = function (x, options)
    if (is.null(options$table))
        default_output_hook(x, options)
    else {
        extra_opts <- if (is.list(options$table)) options$table else list()
        paste(kable(do.call(reparse, c(x, options$comment, extra_opts))),
              collapse = '\n')
    }
)

This will break if the R markdown comment option is set to a character sequence containing a regular expression special char (e.g. *), because R doesn’t seem to have an obvious means of escaping a regular expression.

Here’s a usage example:

```{r table=TRUE}
data.frame(A=1:3, B=4:6)
```

You can pass extra arguments to the deparse function. This is necessary e.g. when the table contains NA values because read.table by default interprets them as strings:

```{r table=list(colClasses=c('numeric', 'numeric'))}
data.frame(A=c(1, 2, NA, 3), B=c(4:6, NA))
```

Far from perfect, but at least it works (for many cases).


Nowadays one can set df_print in the YAML header:

---
output:
  html_document:
    df_print: kable  
---

```{r}
head(iris)
```

I think other answers are from a time when the following didn't work, but now we can just do :

```{r results='asis', render=pander::pander}
head(x)
```

Or set this for all chunks in the setup chunk, for instance :

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, render=pander::pander)
```

Tags:

Markdown

R

Knitr