Sunday 15 March 2015

Create and handle an exception in R -


I have to do a task where he throws a special exception and returns a message, and then just check What is the return that is returned is one of my defined 'exceptions', for example, say I have a function:

  divideByX & lt; - If functional (x) {# if x then NA throws is an exception (if.na (x)) {return (exception ('x' (n '')} # # If x is the exception, skipping exception (if X == 0) Returns ('Exception can not be divided by zero')} {return (10 / x)}}  / Pre> 

So if x is 0, then this option Returns the returns of 'Can not divide by zero', if X is NA, then this exception returns 'x' and for all the other values ​​of x, the expression of x Then I can run something like this:

  tempList <- list ('a' = 2, 'b' = 0, 'c' = 5, 'D' = A) Loppie (Temple List, Function (X) {If (Exception (X)) {Return (X)} and {Y & LT; - DIWIDEBX ) Returns (Y ^ 2)}})   

So it first checks that the value is one of my defining exceptions and if it gives such a message, it squarees my values , So should return to

  $ a [1] 25 $ b [1] 'zero Sector '$ c [1] 4 $ d [1]' X NA '  

What is the best way? Please tell me that nothing is unclear.

Thank you in advance

Function exceptions to generate an exception A linear hierarchy Which may extend the simple error class

  exception  - Function (class, message) {cond & lt; - Simple error (Message) Category (R) & Lt; - c   

This is your function

# if x is 0, then the exception throws (length (x)! = 1) {exception ("non (Except ("isa" "x is na")} and if (x == 0) {exception ("divibiziro" , "Beed to zero")} 10 / x}

and to generate output you (

  alt (tempList, function) pre> 

or to make exceptions differently from others

  & Gt; Touch (list (NA, 3: 5), function (x) ({+ divideByX (x) +}, isa = function (mistake) {+ warning (error) # warning signal, return NA + NA +}, NonScalar = function (error) {+ stop (err) # fail +})) Error: x is not length 1 Additionally: Warning message: x is    

No comments:

Post a Comment