r - 实现tryCatch R

标签 r error-handling

尝试使用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/

相关文章:

r - 派对工具包 : Change terminal node boxplots to bar graphs that shows mean and standard deviation

css - 定位 R Shiny 的 selectInput 小部件

r - freq() 在打印期间重命名列

针对 r 中的特定条件将字符重新编码为数字

python - 在python中打开应用程序时的错误处理

php - 在 ajax 请求回调中显示 PHP 错误

r - 绘制穿过所有数据点的平滑线

java - 我应该通过重新抛出错误来排除 catch 语句中的错误报告吗?

angular - 无法在Angular2中获取错误消息`

android - Android VideoView-管理错误的网址错误?