knitr: wrapping computer output in HTML tags

非 Y 不嫁゛ 提交于 2019-12-07 13:42:12

问题


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)
````

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)

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.

Can this be done with knitr?

EDIT:

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>

I would like something like this:

<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>

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.


回答1:


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)
```

UPDATE

maybe this helps.

```{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)
```

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



来源:https://stackoverflow.com/questions/21820888/knitr-wrapping-computer-output-in-html-tags

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!