Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating summaries at the top of a knitr report that use variables that are defined later

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]
```
like image 860
rrbest Avatar asked May 09 '14 17:05

rrbest


1 Answers

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.

like image 188
Josh O'Brien Avatar answered Sep 29 '22 15:09

Josh O'Brien