Inline referencing of a code chunk in document

Viewed 93

Suppose there is a code chunk as follows:

```{r mean diff} 
(5-mean(dnorm(40,5,2))/5 
```

I would like to be able to reference this code chunk with its label in inline form in a markdown document, so that the reference is replaced by the output of this chunk. Is there a way to do it?

" the difference is `r mean diff` %."    ##something like this?
1 Answers

I think the answer to your question is "yes, but it's tricky". By default knitr doesn't save the last value computed in a code chunk. In regular code, the last value calculated is saved in .Last.value, but knitr doesn't simulate this.

However, a simple modification lets you do something very similar:

```{r} 
meandiff <- 5-mean(dnorm(40,5,2))/5
meandiff   # if you want the chunk to print its value 
```

and then in the text, use

" the difference is `r meandiff` %."

If you really want to save the last value, it's possible by setting a "render hook". For example, the code below saves the last value, then calls the old hook:

```{r}
.Last.value <- NULL
old_hook <- knitr::opts_chunk$get("render")

knitr::opts_chunk$set(render = function(x, options, ...) {
  .Last.value <<- x
  if (!is.null(old_hook))
    old_hook(x, options, ...)
  else
   knitr::knit_print(x, options, ...)
})
```

```{r mean diff} 
5-mean(dnorm(40,5,2))/5 
```

The value was `r .Last.value`.
Related