Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use hooks to format table in output

Tags:

markdown

r

knitr

Using knitr and R Markdown, I can produce a tabularised output from a matrix using the following command:

```{r results='asis'}
kable(head(x))
```

However, I’m searching for a way to make the kable code implicit since I don’t want to clutter the echoed code with it. Essentially, I want this:

```{r table=TRUE}
head(x)
```

… to yield a formatted tabular (rather than the normal output='markdown') output.

I actually thought this must be pretty straightforward since it’s a pretty obvious requirement, but I cannot find any way to achieve this, either via the documentation or on the web.

My approach to create an output hook fails because once the data arrives at the hook, it’s already formatted and no longer the raw data. Even when specifying results='asis', the hook obtains the output as a character string and not as a matrix. Here’s what I’ve tried:

default_output_hook <- knit_hooks$get('output')
knit_hooks$set(output = function (x, options)
    if (! is.null(options$table))
        kable(x)
    else
        default_output_hook(x, options)
)

But like I said, this fails since x is not the original matrix but rather a character string, and it doesn’t matter which value for the results option I specify.

like image 409
Konrad Rudolph Avatar asked Nov 09 '13 14:11

Konrad Rudolph


2 Answers

Nowadays one can set df_print in the YAML header:

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

```{r}
head(iris)
```
like image 68
Ralf Stubner Avatar answered Oct 19 '22 17:10

Ralf Stubner


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)
```
like image 41
Moody_Mudskipper Avatar answered Oct 19 '22 19:10

Moody_Mudskipper