Source-ing an .R script within a function and passing a variable through (RODBC)

Viewed 12223

I have encountered a bit of a hiccup in something I'm working on. Suppose I have the following simple example. Let...

v <- c(606:608) ## Some vector of integers

I also, have a separate script written (let's just call it foo.R) which has something like (uses the RODBC package):

um <- sqlQuery(artemis,paste("select * from port.tdtf_VaR_Unmatched (",LatestModelRun,")",sep=""))

Now suppose I want to run the following loop function:

test <- function() {
 for (i in 1:length(v)) {
  LatestModelRun <- v[i]
  source("C:/R/foo.r")
  print(unmatched)} }

test() ## Run it

When I do this, I get the following error: Error in paste("\n\tselect * from port.tdtf_VaR_Unmatched (", LatestModelRun, : object 'LatestModelRun' not found

So, somehow it's not reading in the LatestModelRun variable defined within the test function.

Here's the traceback():

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()

Anybody have an idea as to what I'm doing wrong??

Any help is much appreciated!! Thanks!!

3 Answers
Related