我在工作中遇到了一些打嗝。假设我有以下简单示例。让...
v <- c(606:608) ## Some vector of integers
我也写了一个单独的脚本(我们只是称之为foo.R
),它有类似的东西(使用RODBC
包):
um <- sqlQuery(artemis,paste("select * from port.tdtf_VaR_Unmatched (",LatestModelRun,")",sep=""))
现在假设我想运行以下循环函数:
test <- function() {
for (i in 1:length(v)) {
LatestModelRun <- v[i]
source("C:/R/foo.r")
print(unmatched)} }
test() ## Run it
当我这样做时,我收到以下错误:
Error in paste("\n\tselect * from port.tdtf_VaR_Unmatched (", LatestModelRun, :
object 'LatestModelRun' not found
所以,不知道它是不是在LatestModelRun
函数中定义的test
变量中读取。
这是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()
任何人都知道我做错了什么?
非常感谢任何帮助!!谢谢!
答案 0 :(得分:25)
正如我在评论中所说,默认情况下会在全局环境中评估source
代码。设置local=TRUE
以评估调用环境中的代码。
test <- function() {
for (i in 1:length(v)) {
LatestModelRun <- v[i]
source("C:/R/foo.r", local=TRUE)
print(unmatched)
}
}
v <- c(606:608)
test()
# [1] "select * from port.tdtf_VaR_Unmatched (606)"
# [1] "select * from port.tdtf_VaR_Unmatched (607)"
# [1] "select * from port.tdtf_VaR_Unmatched (608)"
foo.r
包含:
unmatched <-
paste("select * from port.tdtf_VaR_Unmatched (",LatestModelRun,")",sep="")
答案 1 :(得分:6)
约书亚的回答很甜蜜。简单。我有一个变体,允许您更明确地将参数传递给脚本:
test <- function() {
for (i in 1:length(v)) {
e <- new.env()
e$LatestModelRun <- v[i]
sys.source('c:/R/foo.R', e)
print(e$unmatched)
}
}
这使用堂兄source
;允许您指定环境的sys.source
。
环境实际上也可以是一个列表,所以如果你不需要脚本中的任何结果变量,
你只需传递一个包含所需参数的列表:
sys.source('c:/R/bar.R', list(someparam=42, anotherparam=1:10))
答案 2 :(得分:-1)
函数中设置的变量不是全局的,除非由<<-
设置,所以这不起作用吗?
test <- function() {
for (i in 1:length(v)) {
LatestModelRun <<- v[i]
source("C:/R/foo.r")
print(unmatched)
}
}