Shelby McIntyre
2012-Aug-22 18:28 UTC
[R] Loop for readLines(URL[i]) fails when URL returns Error 404
I have a loop over readLines(URL[i]) which works fine until it hits a bad URL (e.g., a URL that returns a 404 Error). How can I handle this with a test for this error condition. I read the tryCatch( ? ) description but can't figure out how to apply it here. Perhaps there is something else that would work better.
Noia Raindrops
2012-Aug-22 19:39 UTC
[R] Loop for readLines(URL[i]) fails when URL returns Error 404
Hello, For example: url <- c("http://www.example.com", "http://www.example5.com") res <- vector("list", length(url)) for (i in 1:length(url)) res[[i]] <- try(readLines(url[i]), silent = TRUE) res[[2]] ## [1] "Error in file(con, \"r\") : cannot open the connection\n" ## attr(,"class") ## [1] "try-error" ## attr(,"condition") ## <simpleError in file(con, "r"): cannot open the connection> # or for (i in 1:length(url)) res[[i]] <- tryCatch(readLines(url[i]), error = function (e) conditionMessage(e)) res[[2]] ## [1] "cannot open the connection" -- Noia Raindrops noia.raindrops at gmail.com