Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
274 views
in Technique[技术] by (71.8m points)

r - catching an error and then branching logic

How do I write R code that allows me to execute a different path in my code if an error condition happens? I'm using a function that tends to throw an error. When it meets an error condition I would like to execute a different function. Here's a specific example:

require(SuppDists)
parms <- structure(list(gamma = -0.841109044800762, delta = 0.768672140584442, 
    xi = -0.359199299528801, lambda = 0.522761187947026, type = "SB"), .Names = c("gamma", 
"delta", "xi", "lambda", "type"))
pJohnson(.18, parms)

the pJohnson function should fail with the following error:

 Error in pJohnson(0.18, parms) :
 Sb values out of range.

I can make the error go silent by using:

try( pJohnson(.18, parms), silent=T)

but what I really want to do is execute the function alternativeFunction() if pJohnson(.18, parms) returns an error.

It seems like the withCallingHandlers() function should help me out, but I can't figure out how to capture the error and make it run the alternativeFunction() only upon an error condition.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
t <- try(pJohnson(.18, parms))
if("try-error" %in% class(t)) alternativeFunction()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...