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
.
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
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.