The knitr::read_chunk
function is great for referencing chunks in documents. For example, given an annotated R script:
# test.R
## ---- scatter ----------
x <- rnorm(100)
y <- rnorm(100)
plot(y ~ x, pch = 19)
## ---- hists ----------
par(mfrow = c(1, 2))
hist(x)
hist(y)
...I can then reference chunks in a document:
# main.Rnw
\documentclass{article}
\begin{document}
<<setup>>=
library(knitr)
read_chunk("test.R")
@
\begin{figure}
<<scatter>>=
@
\end{figure}
\begin{figure}
<<hists>>=
@
\end{figure}
\end{document}
My questions is: Is there a way to do this inline? I'm looking for a way to do something like:
\begin{figure}
\Sexpr{knit_chunk("scatter")}
\end{figure}
...or perhaps something like...
\Sexpr{"<<scatter>>"}
...which will have the same exact effect as:
\begin{figure}
<<scatter>>=
@
\end{figure}
It doesn't have to be knitr
-- perhaps this is something that can be accomplished with bookdown
text references?
BONUS: It would be even more awesome if I could set the chunk options in the R script as well. I know that knitr::spin
(and knitr::spin_child
) let you do something like this:
# test.R
#+ scatter, fig.width = 3, fig.height = 3
plot(y ~ x)
It would be awesome if there was analogous syntax for chunk references -- i.e. if this would work:
# test.R
## ---- scatter, fig.width = 3, --------
plot(y ~ x)
Alternatively, perhaps the solution to this is to somehow knitr::spin/knitr::spin_child
, but only on specific chunks?