Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: add elements to list in a loop in a tryCatch

I'm trying to parse JSON contained in a dataframe column, some of which is corrupted. As a first step I want to identify the corrupted rows, and use that to subset the dataframe.

I'm using the trick from this post using c() to populate the list (even though I know it's slow):

myRows <- c()
for (i in 1:nrow(myDataframe)) {
  tryCatch({myDataframe$myJSONstring[i] %>%
    fromJSON() %>%
    length()},
    error = function(e) {print(i); myRows <- c(myRows, i)})
}

However, this doesn't work. print(i) works fine, but after running the loop myRows is still just an empty list. Is there some restriction on what code can run in the error bit of a tryCatch?

like image 290
Tom Wagstaff Avatar asked Sep 19 '25 18:09

Tom Wagstaff


1 Answers

Though there already is an accepted answer, I will post another way, without creating an environment.
If the result of tryCatch is assigned to a variable, it can be tested later. The trick is to return the error in the error function.
Example based on the accepted answer, same errors.

vec <- rep(1:0, each = 5)

ans <- lapply(seq_along(vec), function(i) {
  tryCatch({ if(vec[i]) stop("error message") else "success" },
           error = function(e) e)
})

bad <- sapply(ans, inherits, "error")
#[1]  TRUE  TRUE  TRUE  TRUE  TRUE FALSE FALSE FALSE FALSE FALSE
like image 147
Rui Barradas Avatar answered Sep 22 '25 06:09

Rui Barradas