title: Source-ing an .R script within a function and passing a variable through (RODBC)
body: <p>I have encountered a bit of a hiccup in something I'm working on. Suppose I have the following simple example. Let...</p>
  
  <pre><code>v &lt;- c(606:608) ## Some vector of integers
  </code></pre>
  
  <p>I also, have a <strong>separate script</strong> written (let's just call it <code>foo.R</code>) which has something like (uses the <code>RODBC</code> package):</p>
  
  <pre><code>um &lt;- sqlQuery(artemis,paste("select * from port.tdtf_VaR_Unmatched (",LatestModelRun,")",sep=""))
  </code></pre>
  
  <p>Now suppose I want to run the following loop function:</p>
  
  <pre><code>test &lt;- function() {
   for (i in 1:length(v)) {
    LatestModelRun &lt;- v[i]
    source("C:/R/foo.r")
    print(unmatched)} }
  
  test() ## Run it
  </code></pre>
  
  <p>When I do this, I get the following error:
  <code>Error in paste("\n\tselect * from port.tdtf_VaR_Unmatched (", LatestModelRun,  : 
    object 'LatestModelRun' not found</code></p>
  
  <p>So, somehow it's not reading in the <code>LatestModelRun</code> variable defined within the <code>test</code> function.</p>
  
  <p>Here's the <code>traceback()</code>:</p>
  
  <pre><code>7: paste("\n\tselect * from port.tdtf_VaR_Unmatched (", LatestModelRun, 
     ")\n\twhere [PortfolioProduct] not in ('REC - Generic','REC - Green-e NY')\n\torder by [PortfolioProduct], [Year]", 
     sep = "")
  6: odbcQuery(channel, query, rows_at_time)
  5: sqlQuery(artemis, paste("\n\tselect * from port.tdtf_VaR_Unmatched (", 
     LatestModelRun, ")\n\twhere [PortfolioProduct] not in ('REC - Generic','REC - Green-e NY')\n\torder by [PortfolioProduct], [Year]", 
     sep = ""))
  4: eval.with.vis(expr, envir, enclos)
  3: eval.with.vis(ei, envir)
  2: source("C:/R/foo.r")
  1: test()
  </code></pre>
  
  <p>Anybody have an idea as to what I'm doing wrong??</p>
  
  <p>Any help is much appreciated!! Thanks!!</p>