Search code examples
rlatexknitrsweavernw

Only run knitr on parts of Rnw file that have changed


Say I have two code blocks contained within an Rnw file, code_block_1 and code_block_2. Lets say I make to changes to code_block_1 but code_block_2 remains unchanged.

I'm using knitr to convert the Rnw file to a tex file. Because code_block_2 has remained unchanged, can I have knitr only evaluate and run code_block_1?


Solution

  • First check out knitr's options here: http://yihui.name/knitr/options/. I think what you're looking for is the cache option. Try this small example and notice that the times change from one run to the other only for the chunk where you've actually changed the code:

    First run:

    \documentclass{article}
    \begin{document}
    
    <<code_block_1, cache=TRUE>>=
    set.seed(123)
    x <- rnorm(10)
    summary(x)
    Sys.time()
    @
    
    <<code_block_2, cache=TRUE>>=
    set.seed(123)
    y <- rnorm(10)
    summary(y)
    Sys.time()
    @
    
    \end{document}
    

    Output:

    im1

    Second run (after adding a comment in the second chunk):

    \documentclass{article}
    \begin{document}
    
    <<code_block_1, cache=TRUE>>=
    set.seed(123)
    x <- rnorm(10)
    summary(x)
    Sys.time()
    @
    
    <<code_block_2, cache=TRUE>>=
    # Just added a comment in this chunk
    set.seed(123)
    y <- rnorm(10)
    summary(y)
    Sys.time()
    @
    
    \end{document}
    

    Output:

    im2