knitr:将计算机输出包装在HTML标记中 [英] knitr: wrapping computer output in HTML tags

查看:64
本文介绍了knitr:将计算机输出包装在HTML标记中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用knitr,我试图将输出包装在特定类的div中.例如,下面是代码:

With knitr, I'm trying to get the output wrapped in a div of a particular class. For example, here's the code:

```{r}
# Print the pressure data set
head(pressure)
````

我希望将输出(而不是代码)包装在div中,例如<div class='myclass'>,因为该类提供了对输出的特殊控制. (就我而言,它将显示在两列中)

I want the output (but not the code) to be wrapped in a div, like <div class='myclass'>, because the class provides special control over the output. (In my case, it will display in 2 columns)

我在StackOverflow上发现了另一个问题,但提供的答案将代码和输出包装在div中,而我只希望输出在div中.

I found this other question on StackOverflow, but the answer provided wraps the code and output in the div, whereas I just want the output to go in the div.

可以用编织器完成吗?

以下是当前生成的内容:

Here's what's currently generated:

<pre class="r"><code>head(pressure)</code></pre>
<pre><code>##   temperature pressure
## 1           0   0.0002
## 2          20   0.0012
## 3          40   0.0060
## 4          60   0.0300
## 5          80   0.0900
## 6         100   0.2700</code></pre>

我想要这样的东西:

<pre class="r"><code>head(pressure)</code></pre>
<div class="myclass">
<pre><code>##   temperature pressure
## 1           0   0.0002
## 2          20   0.0012
## 3          40   0.0060
## 4          60   0.0300
## 5          80   0.0900
## 6         100   0.2700</code></pre>
</div>

但是我希望它可以针对特定的块进行定制.也就是说,我希望能够设置块选项,以便某些块使用myclass输出,而另一些块使用otherclass输出.

But I would like it to be customizable for particular chunks. That is, I'd like to be able to set chunk options so that some chunks have output with myclass and others have output with otherclass.

推荐答案

以下是一种最小的示例:

Here is a kind of minimal example:

```{r setup, include=FALSE, cache=FALSE, results='asis'}
knit_hooks$set(
  output = function(x, options) {
    # any decoration here
    paste0("<div class='myout'>", x, "</div><br/>")
    }
  )

```

<style>
.myout {background:red}
</style>

```{r}
mean(1:3)
sd(1:3)
var(1:3)
```


更新

也许这会有所帮助.

```{r setup, include=FALSE, cache=FALSE, results='asis'}
ho0 <- knit_hooks$get('output')

knit_hooks$set(
  output = function(x, options) {
    if (is.null(options$class)) ho0(x)
    else 
      # any decoration here
      paste0("<div class='", options$class, "'>", ho0(x), "</div><br/>")
    }
  )

```

<style>
.myout {background:red}
.myout2 {background:skyblue}
</style>

```{r}
mean(1:3)
```
```{r class="myout"}
sd(1:3)
```
```{r class="myout2"}
var(1:3)
```

请注意,您可以在.Rmd之外定义钩子. 在knit之前致电knit_hook$set.

Note that you can define the hook outside the .Rmd. Call knit_hook$set before knit.

这篇关于knitr:将计算机输出包装在HTML标记中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆