Lapply的错误处理 [英] Error Handling with Lapply

查看:61
本文介绍了Lapply的错误处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在R中运行以下代码:

I am trying to run the following code in R:

player1_html=lapply(player1,readLines)

其中,player1是由15个字符向量组成的字符数组,其中包含要读取的不同页面的url.我面临的问题是某些页面显示404错误,由于该错误而导致程序中断并显示以下错误:

where, player1 is a character array of 15 character vectors containing urls of different pages to be read. The problem I am facing is that some of the pages are giving 404 error due to which the program breaks giving the following error:

Error in file(con, "r") : cannot open the connection

我想问一下是否有一种方法可以通过忽略产生错误的链接来处理lapply中的问题.另外,使用readLines(不在lapply中)处理这种错误的正常方法是什么?

I would like to ask if there is a way I can handle this in lapply by ignoring the links that give error. Also, what would be the normal approach to deal with such an error while using readLines(not in lapply)?

推荐答案

再一次,装饰器是一种可行的好方法:

Again, decorator is one of the possible good way to go:

strongify <- function(f)
{
    function(...){
        tryCatch({
            f(...)
        },
    error=function(e) return(NA)
    })
}

strongReadLines = strongify(readLines)

player1_html = lapply(player1,strongReadLines)

发生错误时给您 NA .显然,您装饰的函数不应返回 NA ...或装饰您的装饰器!

Giving you NA when an error occurs. Obviously the function you decorate should not return NA ...or pimp your decorator!

这篇关于Lapply的错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆