I am trying to do the following:
try(htmlParse(ip[1], T)
,
where I define a as:
ip[1] = paste('http://en.wikipedia.org/wiki/George_Clooney')
I want to check if the htmlParse worked or not. For many names in my list, there will be no wikipedia sites and thus I need to be able to check and replace ip[1] with NA if the wiki pages does not exist.
Can someone please advise how I can do that. I tried using the command geterrmessage(), however I am not sure how to flush that everytime I change the name of the celebrity.
Currently I have the following:
if(!isTRUE(as.logical(grep(ip[1],err)))) {
ip[1] = NA
}
else {
This is definately incorrect as it is not running the logical statement I want.
Thanks
Amar
In R Programming, there are basically two ways in which we can implement an error handling mechanism. Either we can directly call the functions like stop() or warning(), or we can use the error options such as “warn” or “warning. expression”.
tryCatch returns the value associated to executing expr unless there's an error or a warning. In this case, specific return values (see return(NA) above) can be specified by supplying a respective handler function (see arguments error and warning in ? tryCatch ).
How do I suppress an error in R? The simplest way of handling conditions in R is to simply ignore them: Ignore errors with try() . Ignore warnings with suppressWarnings() . Ignore messages with suppressMessages() .
This simple example should help you out, I think:
res <- try(log("a"),silent = TRUE)
class(res) == "try-error"
[1] TRUE
The basic idea is the try
returns (invisibly) an object of class "try-error" when there's an error. Otherwise, res
will contain the result of the expression you pass to try
. i.e.
res <- try(log(2),silent = TRUE)
res
[1] 0.6931472
Spend some time reading ?try
carefully, including the examples (which aren't as simple as they could be, I guess). As GSee notes below, a more idiomatic way to check if an error is thrown is to use inherits(res,'try-error')
.
I would try to download all the names (existing or not) from wiki and save it in separate files.I would then grep the following string Wikipedia does not have an article with this exact name and for the non-existing ones I would get a TRUE value. In this way I believe you'll make sure whether the parser worked or the name didn't exist. Additionally you can sort the downloaded files based on their size in case you are suspecting that something went wrong. Corrupted ones have smaller size.
Additionally I would use tryCatch
function in order to treat the logical status:
x<-3
tryCatch(x>5,error=print("this is an error"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With