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] "开发者_Python百科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.
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.
Yes, as in most developed languages, there is such a mechanism. Check ?try.
加载中,请稍侯......
精彩评论