[R] How to check for existence url from within a function?
Duncan Murdoch
murdoch at stats.uwo.ca
Sat May 26 14:02:11 CEST 2007
On 26/05/2007 7:13 AM, Heinz Tuechler wrote:
> Dear All,
>
> To check if an url exists, I can use try(). This works, as I expected, if I
> do it directly, as in the first part of the following example, but I could
> not find a way to do it from within a function, as in the second part.
>
> Where could I find information on how to do this?
>
> Thanks,
> Heinz
>
>
> ## set nonexisting url
> url.string <- 'http://www.google.at/nonexist.html'
>
> ## first part
> 1 # to start with defined .Last.value
> try(con.url <- url(url.string, open='rb'))
> class.try.res <- class(.Last.value)
> try.error <- class.try.res== 'try-error'
> print(try.error) # TRUE
> try(close(con.url))
>
> ## try() within a function
> url.error <- function(url.string) {
> 1 # to start with defined .Last.value
> try(con.url <- url(url.string, open='rb'))
> class.try.res <- class(.Last.value)
> try.error <- class.try.res== 'try-error'
.Last.value isn't set until your function returns. You should write this as
con.url <- try(url(url.string, open='rb'))
try.error <- inherits(con.url, "try-error")
Notice that I used "inherits", rather than testing for equality. It's
documented that the result of try() will be "of class 'try-error'" if an
error occurs, but there may be circumstances (in the future?) where
different types of errors are signalled by using a more complicated class.
Duncan Murdoch
> print(try.error)
> try(close(con.url))
> invisible(try.error)
> }
>
> ## call the function
> url.error(url.string) # result -> FALSE
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list