3

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 adds the name.
<<part2>>=
  print(x)}
@
\end{document}
1
  • 1
    You could just set the chunk option eval to FALSE? Another possibility would be to use the listings package?
    – Adam Liter
    May 8 '14 at 22:32
2

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 adds the name.
<<part2, eval=FALSE>>=
  print(x)}
@

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

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

\end{document}

enter image description here

2
  • 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.
    – Dan Wright
    May 9 '14 at 13:29
  • 1
    @DanWright You can combine the two chunks into a third chunk, then evaluate it, e.g. <<part3, ref.label=c('part1', 'part2')>>>=
    – Yihui Xie
    May 9 '14 at 17:00
3

Read up on the chunk options available and see how to use them.

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>>=
@
0

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")
@
Part2 adds the name.
<<part2,eval=FALSE>>=
  print(x)}
@
<<part3,echo=FALSE,ref.label=c('part1','part2')>>=
@
<<executefunction>>=
hello('Adam and Yihue')
@
\end{document}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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