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?
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
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