问题
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