lokheart
lokheart

Reputation: 24665

Bypassing an error inside a loop in R

I have a dummy script below:

a <- 1
b <- 2
c <- 3
e <- 5

list <- letters[1:5]

for (loop in (1:length(list)))
    {print(paste(list[loop],get(list[loop]),sep="-"))
    }

> source('~/.active-rstudio-document')
[1] "a-1"
[1] "b-2"
[1] "c-3"
Error in get(list[loop]) : object 'd' not found

Currently I have a problem that since d is not present, so an error message pop up and block the processing of e.

I wonder if R has some kind of "error handling", that is to bypass the error due to d, keep processing e, then return the error message when all valid data are processed.

Thanks.

Upvotes: 2

Views: 1273

Answers (2)

Andrie
Andrie

Reputation: 179428

Use exists to check whether a variable exists:

for (loop in (1:length(list))){
  if(exists(list[loop])){
    print(
        paste(list[loop], get(list[loop]), sep="-"))
  }
}

[1] "a-1"
[1] "b-2"
[1] "c-3"
[1] "e-5"

More generally, R has a sophisticated mechanism for catching and dealing with errors. See ?tryCatch and its simplified wrapper, ?try, for more details.

Upvotes: 5

Nick Sabbe
Nick Sabbe

Reputation: 11956

Yes, as in most developed languages, there is such a mechanism. Check ?try.

Upvotes: 2

Related Questions