Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
366 views
in Technique[技术] by (71.8m points)

r - Use hooks to format table in output

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Nowadays one can set df_print in the YAML header:

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...