title: How to keep R and Rnw files separate when R code is complex
body: <p>I want to use <code>knitr</code> to generate a dynamic document based on results produced by a long/complex R script.
  I have the following requirement:</p>
  
  <ul>
  <li>The Rnw file only contains latex and short knitr chunks, by short I mean something like </li>
  </ul>
  
  <p><code>
  &lt;&lt;chunk1&gt;&gt;=
  plotData &lt;- getData(some,arguments)
  somePlottingFunction(plotData)
  @
  </code>
  or</p>
  
  <p><code>&lt;&lt;chunk2&gt;&gt;=
  plotData &lt;- getData(some,arguments)
  xTable(plotData)
  @
  </code>
  I mean I do not want to have large portion of <code>R</code> code mixed with <code>latex</code></p>
  
  <p>What I was doing up to now was to execute a <code>R</code> script that would leave some <code>R</code> objects in the workspace that would then be used and knit.</p>
  
  <pre><code>runFunctionAndKnit &lt;- function(){
     source('theRscript.R')
     knit('theRnwFile.Rnw')
  }
  </code></pre>
  
  <p>Problem arise when I use very large objects, I just cannot afford to leave temporary objects waiting to be knit at the end of the script (not enough RAM) </p>
  
  <p>I red quickly the <a href="https://www.crcpress.com/Dynamic-Documents-with-R-and-knitr/Xie/9781482203530" rel="nofollow">knitr book</a> (about externalisation) but could not find a solution. Can't I do anything else than saving objects to be loaded/knit afterwards (this looks like it is killing the purpose of <code>knitr</code>) ?</p>
  
  <p>As an example say I have some R code like this:</p>
  
  <pre><code>main &lt;- function(){
     #some stuff on 10s on lines
  
     ## @knitr chunk1
     # ...
     ## @knitr
  
     f1 &lt;- function(){
       #some code
       ## @knitr chunk2
       #some stuff I'd like to knit
       ## @knitr
     }
     f1()
  
     #some other stuff
  
     ## @knitr chunk3
     # ...
     ## @knitr
  }
  </code></pre>
  
  <p>Is there some way of kniting the following <code>Rnw</code> file (some R objects might be destroyed because of scope):</p>
  
  <p><code>&lt;&lt;chunk1&gt;&gt;=
  @
  &lt;&lt;chunk2&gt;&gt;=
  @
  &lt;&lt;chunk3&gt;&gt;=
  @
  </code></p>