使用挂钩在输出中格式化表格 [英] Use hooks to format table in output
问题描述
使用knitr和R Markdown,我可以使用以下命令从矩阵生成表格化的输出:
Using knitr and R Markdown, I can produce a tabularised output from a matrix using the following command:
```{r results='asis'}
kable(head(x))
```
但是,我正在寻找一种使kable
代码隐式的方法,因为我不想使回显的代码变得混乱.本质上,我想要这样:
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)
```
…产生格式化的表格格式(而不是普通的output='markdown'
)输出.
… 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.
我创建输出挂钩的方法失败了,因为一旦数据到达挂钩,它便已经被 格式化并且不再是原始数据.即使指定了results='asis'
,该钩子也将获得的输出作为字符串而不是矩阵.这是我尝试过的:
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)
)
但是就像我说的那样,这失败了,因为x
不是原始矩阵,而是字符串,并且对于results
选项指定哪个值都没有关系.
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.
推荐答案
我认为其他答案是从以下方法不起作用的时候开始的,但是现在我们可以做到了:
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)
```
这篇关于使用挂钩在输出中格式化表格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!