I typically like to have my chunks in a manner that is coherent for someone (me) reading the code. For example, I'll often have some text declaring what I'm trying to achieve, what is in the following figure(s), and whether there's some statistical difference e.g. 'In figure 1.1 we show x and y... mean = .... (p < 0.05)'. Then I'll have 2 chunks, one for the graph, followed by a chunk that finds summary info (means, medians, etc) and some statistical analysis.
The problem I have is referencing within the text before the chunks. It works fine for figure references, but I can't reference variables before they're defined. Below is a MWE hopefully illustrating what I mean. Is there any way around this? The obvious answer is to move the summary stats chunk before the paragraph of text, but I find this more confusing when I revisit the code.
I can reference figures before they're plotted: Figure \@ref(fig:cars-plot) but not other things: `r mean_speed`.
```{r cars-plot, fig.cap = "plot of cars"}
plot(cars)
```
```{r}
mean_speed <- mean(cars$speed)
```
Which throws the following error, because I'm trying to call it before the chunk is executed:
Error in eval(parse_only(code), envir = envir) : object 'mean_speed' not found