YNWA1992
YNWA1992

Reputation: 99

Is it possible to write if-statement for errors in r?

for example, I want to fill in empty lists by lots of data frames(using web-scraping). The most part of web data behaves nicely, but minor part not(for example, the absence of data in imdb rating's page).

Is it possible to create an if-statement, such that:

if(Error "bla-bla-bla" exists){
    then create data.frame(that consists of NA's)
    and add data.frame to list

It will be nice to see a pattern or smth like that. Many thanks!

Upvotes: 0

Views: 51

Answers (1)

csgillespie
csgillespie

Reputation: 60452

The simplest way is to use try and examine the class of the object:

x = "5"
y = try(x+x, silent=TRUE)
if(class(y) == "try-catch") {
  ## Do something
}

If you examine y,

R> y
[1] "Error in x + x : non-numeric argument to binary operator\n"
attr(,"class")
[1] "try-error"
attr(,"condition")
<simpleError in x + x: non-numeric argument to binary operator>

You can extract the error message, attr(y, "condition"). Also look at tryCatch.

Upvotes: 1

Related Questions