尝试使用tryCatch
。我想要的是遍历存储在page1URLs
中的URL列表,如果其中一个存在问题(使用readHTMLTable()
),我想要记录哪些URL,然后希望代码继续进行下一个网址而不会崩溃。
我想我这里根本没有正确的主意。谁能建议我该怎么做?
这是代码的开头:
baddy <- rep(NA,10,000)
badURLs <- function(url) { baddy=c(baddy,url) }
writeURLsToCsvExtrema(38.361042, 35.465144, 141.410522, 139.564819)
writeURLsToCsvExtrema <- function(maxlat, minlat, maxlong, minlong) {
urlsFuku <- page1URLs
allFuku <- data.frame() # need to initialize it with column names
for (url in urlsFuku) {
tryCatch(temp.tables=readHTMLTable(url), finally=badURLs(url))
temp.df <- temp.tables[[3]]
lastrow <- nrow(temp.df)
temp.df <- temp.df[-c(lastrow-1,lastrow),]
}
最佳答案
一种通用方法是编写一个完全处理一个URL的函数,返回计算值或NULL以指示失败
FUN = function(url) {
tryCatch({
xx <- readHTMLTable(url) ## will sometimes fail, invoking 'error' below
## more calculations
xx ## final value
}, error=function(err) {
## what to do on error? could return conditionMessage(err) or other...
NULL
})
}
然后例如将其与命名 vector 一起使用
urls <- c("http://cran.r-project.org", "http://stackoverflow.com",
"http://foo.bar")
names(urls) <- urls # add names to urls, so 'result' elements are named
result <- lapply(urls, FUN)
这些家伙失败了(返回NULL)
> names(result)[sapply(result, is.null)]
[1] "http://foo.bar"
这些是进一步处理的结果
final <- Filter(Negate(is.null), result)
关于r - 实现tryCatch R,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22784342/