15

Is there a standard way to include the computed values from variables early on in the written knitr report before those values are computed in the code itself? The purpose is to create an executive summary at the top of the report.

For example, something like this, where variable1 and variable2 are not defined until later:

---
title: "Untitled"
output: html_document
---

# Summary
The values from the analysis are `r variable1` and `r variable2`

## Section 1

In this section we compute some values. We find that the value of variable 1 is `r variable1`

```{r first code block}
variable1 <- cars[4, 2]
```

## Section 2

In this section we compute some more values. In this section we compute some values. We find that the value of       variable 2 is `r variable2`

```{r second code block}
variable2 <- cars[5, 2]
```

5 Answers 5

6

A simple solution is to simply knit() the document twice from a fresh Rgui session.

The first time through, the inline R code will trigger some complaints about variables that can't be found, but the chunks will be evaluated, and the variables they return will be left in the global workspace. The second time through, the inline R code will find those variables and substitute in their values without complaint:

knit("eg.Rmd")
knit2html("eg.Rmd")

## RStudio users will need to explicitly set knit's environment, like so:    
# knit("eg.Rmd", envir=.GlobalEnv)
# knit2html("eg.Rmd", envir=.GlobalEnv)

enter image description here


Note 1: In an earlier version of this answer, I had suggested doing knit(purl("eg.Rmd")); knit2html("eg.Rmd"). This had the (minor) advantage of not running the inline R code the first time through, but has the (potentially major) disadvantage of missing out on knitr caching capabilities.

Note 2 (for Rstudio users): RStudio necessitates an explicit envir=.GlobalEnv because, as documented here, it by default runs knit() in a separate process and environment. It default behavior aims to avoid touching anything in global environment, which means that the first run won't leave the needed variables lying around anywhere that the second run can find them.

5

Here is another approach, which uses brew + knit. The idea is to let knitr make a first pass on the document, and then running it through brew. You can automate this workflow by introducing the brew step as a document hook that is run after knitr is done with its magic. Note that you will have to use brew markup <%= variable %> to print values in place.

---
title: "Untitled"
output: html_document
---

# Summary

The values from the analysis are <%= variable1 %> and 
<%= variable2 %>

## Section 1

In this section we compute some values. We find that the value of variable 1 
is <%= variable1 %>


```{r first code block}
variable1 = cars[6, 2]
```


## Section 2

In this section we compute some more values. In this section we compute 
some values. We find that the value of  variable 2 is <%= variable2 %>

```{r second code block}
variable2 = cars[5, 2]
```

```{r cache = F}
require(knitr)
knit_hooks$set(document = function(x){
  x1 = paste(x, collapse = '\n')
  paste(capture.output(brew::brew(text = x1)), collapse = '\n')
})
```
5

This has become pretty easy using the ref.label chunk option. See below:

--- 
title: Report
output: html_document
---

```{r}
library(pixiedust)
options(pixiedust_print_method = "html")
```

### Executive Summary 

```{r exec-summary, echo = FALSE, ref.label = c("model", "table")}
```

Now I can make reference to `fit` here, even though it isn't yet defined in the script. For example, a can get the slope for the `qsec` variable by calling `round(coef(fit)[2], 2)`, which yields 0.93.

Next, I want to show the full table of results. This is stored in the `fittab` object created in the `"table"` chunk.

```{r, echo = FALSE}
fittab
```

### Results

Then I need a chunk named `"model"` in which I define a model of some kind.

```{r model}
fit <- lm(mpg ~ qsec + wt, data = mtcars)
```

And lastly, I create the `"table"` chunk to generate `fittab`.

```{r table}
fittab <- 
  dust(fit) %>%
  medley_model() %>% 
  medley_bw() %>% 
  sprinkle(pad = 4,
           bg_pattern_by = "rows")
```
1
  • Seems this doesn't work with the child options though.
    – s_baldur
    Oct 23, 2018 at 13:17
1

I work in knitr, and the following two-pass system works for me. I have two (invisible) code chunks, one at the top and one at the bottom. The one at the bottom saves the values of any variables I need to include in the text before they are actually computed in a file (statedata.R). The top chunk sets the variable values to something that stands out if they haven't been defined yet, and then (if it exists) it grabs the actual values from the stored file.

The script needs to be knit twice, as values will be available only after one pass through. Note that the second chunk erases the saved state file at the end of the second pass, so that any later changes to the script that affect the saved variables will have to be computed anew (so that we don't accidentally report old values from an earlier run of the script).

---
title: "Untitled"
output: html_document
---
```{r, echo=FALSE, results='hide'}
# grab saved computed values from earlier passes
if (!exists("variable1")) {
        variable1 <- "UNDEFINED"
        variable2 <- "UNDEFINED"
        if (file.exists("statedata.R")) {
                source("statedata.R")
        }
}

# Summary
The values from the analysis are `r variable1` and `r variable2`

## Section 1

In this section we compute some values. We find that the value of variable 1 is `r variable1`

```{r first code block}
variable1 <- cars[4, 2]
```

## Section 2

In this section we compute some more values. In this section we compute some values. We find that the value of       variable 2 is `r variable2`

```{r second code block}
variable2 <- cars[5, 2]
```
```{r save variables for summary,echo=FALSE,results='hide'}
if (!file.exists("statedata.R")) {
        dump(c("variable1","variable2"), file="statedata.R")
        } else {
        file.remove("statedata.R")
}
```
0

Latex macros can solve this problem. See this answer to my related question.

\newcommand\body{

\section{Analysis}

<<>>= 
x <- 2
@

Some text here

}  % Finishes body

\section*{Executive Summary}

<<>>=
x
@

\body

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.