Error Handling with Lapply

烈酒焚心 提交于 2019-12-11 13:37:53

问题


I am trying to run the following code in R:

player1_html=lapply(player1,readLines)

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

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)?


回答1:


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)

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



来源:https://stackoverflow.com/questions/27721097/error-handling-with-lapply

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!