我正在使用 getYahooData()
函数在 TTR 包装相当激烈。
我有这段代码:
for(i in 1:nrow(symbol)){
tryCatch(prices <- getYahooData(symbol$symbol[i], from, to, freq="daily",
type="price"),
warning=function(e) continue <- 0)
if (continue==0) next
}
这个循环很长我收到这个错误:
Error in file(file, "rt") : all connections are in use Calls: tryCatch ... doTryCatch -> getYahooData -> getYahooData -> read.table -> file Execution halted
我能做什么?
更新:
如果我使用 closeAllConnections() 我得到:
I get: *** caught segfault *** address (nil), cause 'memory not mapped' Traceback: 1: getConnection(set[i]) 2: close(getConnection(set[i])) 3: closeAllConnections() aborting ...
最佳答案
第一:永远不要在你的生活中再次使用继续构造。没啥用tryCatch()
如果您为错误或警告定义了处理程序,则将继续。它将使用那个而不是“默认”error=function(e) stop(e)
.这将停止您的功能。如果您定义处理程序( warning=
或 error=
),您的脚本将不会停止,因此不需要继续。
这说:在这种情况下正确使用 tryCatch 是:
for(i in 1:nrow(symbol)){
tryCatch(prices <- getYahooData(symbol$symbol[i], from, to, freq="daily",
type="price"), error = function(e){})
}
或者,如果您在脚本中使用它并希望在发生错误时进入下一个循环,您可以简单地使用:
for(i in 1:nrow(symbol)){
prices <- try(getYahooData(symbol$symbol[i], from, to, freq="daily",
type="price"), silent=TRUE)
if(inherits(prices,"try-error")) { next } # only true if an error occurs
... # rest of calculations
}
如果您使用 tryCatch 或 try 的这种方式,您就不会遇到您在此处报告的问题。
现在我可以重现你的情况,如果我使用不存在的符号。您对
tryCatch()
的错误使用功能正在给您带来麻烦。 read.table
返回错误( Error in file(file, "rt") : cannot open the connection
)。这是一个 错误 ,不是警告。您会收到一条额外的警告,指出返回了未找到的 404 文件。当警告与错误一起发出时,将首先处理警告的处理函数。这是因为在停止函数之前必须抛出警告。所以它不会处理你得到的错误,这意味着
on.exit(close(file))
在 read.table()
不会被调用。因此,连接没有正确关闭并且仍然被认为是打开的,尽管它不能再被 R 找到(showAllConnections() 什么也没显示)。由于错误未得到处理,连接注册出现问题。由于无法打开连接,on.exit(close(...))
不会有任何影响。 showConnections()
没有显示连接,但不知何故 R 仍然认为它在那里。因此,所有的 hell 都崩溃了,你的 R 崩溃了。感谢您对@Tommy 的更正
一个简单的代码示例来说明这一点:
myfun <- function(x){
if(x>1) warning("aWarning")
stop("aStop")
x
}
tryCatch(myfun(0.5),
warning=function(w)print("warning"),
error=function(e) print("stop"))
[1] "stop"
tryCatch(myfun(1.5),
warning=function(w)print("warning"),
error=function(e) print("stop"))
[1] "warning"
总之 :
作为额外的:当您覆盖
prices
时,您的循环只会返回上次调用的结果。每次遍历循环时,以防您使用正确的符号。编辑:如果您想继续操作
关于r - 所有连接都在使用中 : Execution halted,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7103429/