# knitr. Splitting a function into several blocks

Is it possible with knitr to split an R function across several blocks (for documentation reasons)? Here is a MWE:

\documentclass{article}
\begin{document}
Part1 gives salutation.
<<part1>>=
hello <- function(x){
print("Hi")
@
<<part2>>=
print(x)}
@
\end{document}

• You could just set the chunk option eval to FALSE? Another possibility would be to use the listings package? May 8 '14 at 22:32

There is a chunk option called eval, which controls whether or not the code is actually evaluated by R. If you set it to FALSE, then the code will not be evaluated, and so you could, in principle, type whatever you wanted to type.

Additionally, as Yihui points out in the comments, you can use <<part3, ref.label=c('part1', 'part2')>>= to combine your part1 and part2 and actually evaluate the code.

In the following MWE, I've added such a part3, setting echo to FALSE, so that nothing appears, as you already have the code displayed in parts 1 and 2. Then, if you'd like, you can add a part4 where you actually pass an argument to the function that you've defined.

\documentclass{article}

\begin{document}

Part1 gives salutation.
<<part1, eval=FALSE>>=
hello <- function(x){
print("Hi")
@
<<part2, eval=FALSE>>=
print(x)}
@

<<part3, ref.label=c('part1', 'part2'), echo=FALSE>>=
@

<<part4>>=
hello("Dan Wright")
@

\end{document}


• Using echo=FALSE,eval=TRUE with the function block and then just putting the code bits in LaTeX is what I have done before, but it seems against the ethos of knitr since you are not actually running those lines. May 9 '14 at 13:29
• @DanWright You can combine the two chunks into a third chunk, then evaluate it, e.g. <<part3, ref.label=c('part1', 'part2')>>>= May 9 '14 at 17:00

In this paricular case, the echo and eval options can be used together...

<<the_func, echo=FALSE>>=
hello <- function(x){
print("Thanks")
print(x)
}
@

<<the_func, echo=1:2, eval=FALSE>>=
@

<<the_func, echo=3:4, eval=FALSE>>=
@


The ref.label option solves this. Here is the working example.

\documentclass{article}
\begin{document}
Part1 gives salutation.
<<part1,eval=FALSE>>=
hello <- function(x){
print("Thanks")
@