Skip to content Skip to sidebar Skip to footer

Knitr: Wrapping Computer Output In Html Tags

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

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

Post a Comment for "Knitr: Wrapping Computer Output In Html Tags"