Beruflich Dokumente
Kultur Dokumente
R.M. Ripley
Department of Statistics
University of Oxford
2012/13
R Exception Handling
Use of R options
Use of R options
Note that many available options are not set by default. Some are
set as packages are loaded.
The options available can be found by using the help system: the
page for options contains a detailed description.
Note that many available options are not set by default. Some are
set as packages are loaded.
The options available can be found by using the help system: the
page for options contains a detailed description.
Note that many available options are not set by default. Some are
set as packages are loaded.
The options available can be found by using the help system: the
page for options contains a detailed description.
Possible outcomes
Possible outcomes
Possible outcomes
Possible outcomes
Possible outcomes
Possible outcomes
One way to trace errors is to add cat or print statements where you
think they might be enlightening. But R provides several tools for more
powerful debugging. They are also useful for checking intermediate
results.
traceback() Prints the sequence of calls that led to the last error.
browser() Inserted into a function, interrupts it and allows access
to the R interpreter.
debug() Sets a debugging flag on a function: equivalent to
browser() at start of function. undebug() unsets
the flag
trace() Similar to debug but more powerful. untrace()
unsets the flag
recover() Allows browsing on any currently active function call.
Often used as an error option.
R.M. Ripley (University of Oxford) Debugging R Functions 2012/13 8 / 29
Checking and Improving your functions Debugging functions
One way to trace errors is to add cat or print statements where you
think they might be enlightening. But R provides several tools for more
powerful debugging. They are also useful for checking intermediate
results.
traceback() Prints the sequence of calls that led to the last error.
browser() Inserted into a function, interrupts it and allows access
to the R interpreter.
debug() Sets a debugging flag on a function: equivalent to
browser() at start of function. undebug() unsets
the flag
trace() Similar to debug but more powerful. untrace()
unsets the flag
recover() Allows browsing on any currently active function call.
Often used as an error option.
R.M. Ripley (University of Oxford) Debugging R Functions 2012/13 8 / 29
Checking and Improving your functions Debugging functions
One way to trace errors is to add cat or print statements where you
think they might be enlightening. But R provides several tools for more
powerful debugging. They are also useful for checking intermediate
results.
traceback() Prints the sequence of calls that led to the last error.
browser() Inserted into a function, interrupts it and allows access
to the R interpreter.
debug() Sets a debugging flag on a function: equivalent to
browser() at start of function. undebug() unsets
the flag
trace() Similar to debug but more powerful. untrace()
unsets the flag
recover() Allows browsing on any currently active function call.
Often used as an error option.
R.M. Ripley (University of Oxford) Debugging R Functions 2012/13 8 / 29
Checking and Improving your functions Debugging functions
One way to trace errors is to add cat or print statements where you
think they might be enlightening. But R provides several tools for more
powerful debugging. They are also useful for checking intermediate
results.
traceback() Prints the sequence of calls that led to the last error.
browser() Inserted into a function, interrupts it and allows access
to the R interpreter.
debug() Sets a debugging flag on a function: equivalent to
browser() at start of function. undebug() unsets
the flag
trace() Similar to debug but more powerful. untrace()
unsets the flag
recover() Allows browsing on any currently active function call.
Often used as an error option.
R.M. Ripley (University of Oxford) Debugging R Functions 2012/13 8 / 29
Checking and Improving your functions Debugging functions
One way to trace errors is to add cat or print statements where you
think they might be enlightening. But R provides several tools for more
powerful debugging. They are also useful for checking intermediate
results.
traceback() Prints the sequence of calls that led to the last error.
browser() Inserted into a function, interrupts it and allows access
to the R interpreter.
debug() Sets a debugging flag on a function: equivalent to
browser() at start of function. undebug() unsets
the flag
trace() Similar to debug but more powerful. untrace()
unsets the flag
recover() Allows browsing on any currently active function call.
Often used as an error option.
R.M. Ripley (University of Oxford) Debugging R Functions 2012/13 8 / 29
Checking and Improving your functions Debugging functions
traceback
Use after the error: no forward planning required
Example of traceback()
library(MASS)
lda(Sex ~ FL + CL + CW + RW + BD, crabs)
Error in eval(expr,envir,enclos):object "Sex" not
found
traceback()
9: eval(expr, envir, enclos)
8: eval(predvars, data, env)
7: model.frame.default(formula = Sex ~ FL + CL + CW +
RW + BD, data = crabs)
6: model.frame(formula = Sex ~ FL + CL + CW + RW +
BD, data = crabs)
5: eval(expr, envir, enclos)
4: eval(expr, p)
3: eval.parent(m)
2: lda.formula(Sex ~ FL + CL + CW + RW + BD, crabs)
1: lda(Sex ~ FL + CL + CW + RW + BD, crabs)
R.M. Ripley (University of Oxford) Debugging R Functions 2012/13 9 / 29
Checking and Improving your functions Debugging functions
browser()
Need to set up before the function is run. Change the function either by
usual route, or use fix(myfn) to leave your source file unchanged.
Add a call to browser() before the place you suspect the error
occurs. Rerun the job: R will stop with a prompt labelled "Browse":
Example of browser()
mymat<- cbind(1:4,c(1,4:6),4:7)
fn1(mymat)
Error in if (nmul > 1) nmul^3 else nmul^2 :
argument is of length zero
fix(fn1)
fn1(mymat)
Called from: fn1(mymat)
Browse[1]>
browser()
Need to set up before the function is run. Change the function either by
usual route, or use fix(myfn) to leave your source file unchanged.
Add a call to browser() before the place you suspect the error
occurs. Rerun the job: R will stop with a prompt labelled "Browse":
Example of browser()
mymat<- cbind(1:4,c(1,4:6),4:7)
fn1(mymat)
Error in if (nmul > 1) nmul^3 else nmul^2 :
argument is of length zero
fix(fn1)
fn1(mymat)
Called from: fn1(mymat)
Browse[1]>
Use of browser
Use the prompt like a normal one, and enter normal commands, but
there are a few special commands:
c or cont or just return: leave the browser and continue at the
next statement
Q exit the browser and the current function and return to the
toplevel prompt
Note than to examine a variable called c, cont, n, where, or Q, use
print()
Use of browser
Use the prompt like a normal one, and enter normal commands, but
there are a few special commands:
c or cont or just return: leave the browser and continue at the
next statement
Q exit the browser and the current function and return to the
toplevel prompt
Note than to examine a variable called c, cont, n, where, or Q, use
print()
Use of browser
Use the prompt like a normal one, and enter normal commands, but
there are a few special commands:
c or cont or just return: leave the browser and continue at the
next statement
Q exit the browser and the current function and return to the
toplevel prompt
Note than to examine a variable called c, cont, n, where, or Q, use
print()
Use of browser
Use the prompt like a normal one, and enter normal commands, but
there are a few special commands:
c or cont or just return: leave the browser and continue at the
next statement
Q exit the browser and the current function and return to the
toplevel prompt
Note than to examine a variable called c, cont, n, where, or Q, use
print()
Use of browser
Use the prompt like a normal one, and enter normal commands, but
there are a few special commands:
c or cont or just return: leave the browser and continue at the
next statement
Q exit the browser and the current function and return to the
toplevel prompt
Note than to examine a variable called c, cont, n, where, or Q, use
print()
Use of browser
Use the prompt like a normal one, and enter normal commands, but
there are a few special commands:
c or cont or just return: leave the browser and continue at the
next statement
Q exit the browser and the current function and return to the
toplevel prompt
Note than to examine a variable called c, cont, n, where, or Q, use
print()
debug()
debug()
debug(fn1)
fn1(mymat)
debugging in: fn1(mymat)
debug: {
mults <- mat[mat[, 1] == mat[, 2], ]
nmul <- nrow(mults)
if (nmul > 1)
nmul^3
else nmul^2
}
Browse[2]>
Use of debug()
Use the prompt like a normal one, and enter normal commands, but
there are a few special commands, similar to those for browser()
(note c and n behave differently here)
c or cont : continue to the end of the current context (loop or
function)
Q exit the browser and the current function and return to the
toplevel prompt
Use of debug()
Use the prompt like a normal one, and enter normal commands, but
there are a few special commands, similar to those for browser()
(note c and n behave differently here)
c or cont : continue to the end of the current context (loop or
function)
Q exit the browser and the current function and return to the
toplevel prompt
Use of debug()
Use the prompt like a normal one, and enter normal commands, but
there are a few special commands, similar to those for browser()
(note c and n behave differently here)
c or cont : continue to the end of the current context (loop or
function)
Q exit the browser and the current function and return to the
toplevel prompt
Use of debug()
Use the prompt like a normal one, and enter normal commands, but
there are a few special commands, similar to those for browser()
(note c and n behave differently here)
c or cont : continue to the end of the current context (loop or
function)
Q exit the browser and the current function and return to the
toplevel prompt
Use of debug()
Use the prompt like a normal one, and enter normal commands, but
there are a few special commands, similar to those for browser()
(note c and n behave differently here)
c or cont : continue to the end of the current context (loop or
function)
Q exit the browser and the current function and return to the
toplevel prompt
Example of debug()
debug(), continued
Browse[2]> n
debug: mults <- mat[mat[, 1] == mat[, 2], ]
Browse[2]> n
debug: nmul <- nrow(mults)
Browse[2]> mults
[1] 1 1 4
Browse[2]> dim(mults)
NULL
Browse[2]> Q
trace is similar, but with more facilities. Consult the help page for
more details.
R.M. Ripley (University of Oxford) Debugging R Functions 2012/13 16 / 29
Checking and Improving your functions Debugging functions
recover()
recover()
##set up error function
options(error=recover)
##run our function
fn1(mymat)
Error in if (nmul > 1) nmul^3 else nmul^2 :
argument is of length zero
1: fn1(mymat)
Selection:
recover()
recover(), continued
Selection: 1
Called from: eval(expr, envir, enclos)
Browse[1]> ls()
[1] "mat" "mults" "nmul"
Browse[1]> dim(mults)
NULL
Browse[1]> mults
[1] 1 1 4
Browse[1]> c
1: fn1(mymat)
Selection: 0
>
Then fix the function and rerun
R.M. Ripley (University of Oxford) Debugging R Functions 2012/13 18 / 29
Checking and Improving your functions Trapping expected errors
try()
A wrapper for your function, which returns the normal return value,
unless there is an error, when it returns an object of class
"try-error"
If there is an error, it prints an error message, unless you have
suppressed error messages using
options(show.error.messages=FALSE) or used the
argument silent=TRUE.
Surround your function by
if (!inherits(x <- try(myfn(y)), "try-error"))
do normal processing
else
do error processing
try() continued
try()
tmp <- try(solve(mymat[-3, ]))
inherits(tmp, "try-error")
[1] FALSE
tmp <- try(solve(mymat[-1, ]))
inherits(tmp, "try-error")
Error in solve.default(mymat[-1, ]) :
Lapack routine dgesv: system is exactly singular
[1] TRUE
tmp <- try(solve(mymat[-1, ]),silent=TRUE)
inherits(tmp, "try-error")
[1] TRUE
tryCatch
More powerful alternative to try().
expr Here you put the code which might cause an error or warning
finally Here you put code which should always be run (unless your
error handler stops things dead!).
The ... can include handlers for conditions you have defined.
The return value after a trapped condition will have the class of
the return value from the last handler invoked.
tryCatch
More powerful alternative to try().
expr Here you put the code which might cause an error or warning
finally Here you put code which should always be run (unless your
error handler stops things dead!).
The ... can include handlers for conditions you have defined.
The return value after a trapped condition will have the class of
the return value from the last handler invoked.
tryCatch
More powerful alternative to try().
expr Here you put the code which might cause an error or warning
finally Here you put code which should always be run (unless your
error handler stops things dead!).
The ... can include handlers for conditions you have defined.
The return value after a trapped condition will have the class of
the return value from the last handler invoked.
tryCatch, continued
tmp<- tryCatch(solve(mymat[-3,]),error=function(e){
cat("Matrix inversion failed\n"); e})
tmp
[,1] [,2] [,3]
[1,] 0.1666667 -1.4166667 0.9166667
[2,] -0.5000000 0.7500000 -0.2500000
[3,] 0.3333333 0.1666667 -0.1666667
tmp <- tryCatch(solve(mymat[-1,]),error=function(e){
cat("Matrix inversion failed\n"); e})
Matrix inversion failed
tmp
<simpleError in solve.default(mymat[-1, ]): Lapack
routine dgesv: system is exactly singular>
class(tmp)
[1] "simpleError" "error" "condition"
tmp <- tryCatch(solve(mymat[-1, ]), error=function(e) e,
finally=print("END"))
[1] "END"
R.M. Ripley (University of Oxford) Debugging R Functions 2012/13 22 / 29
Checking and Improving your functions Profiling
Profiling
Rprof()
mymat <- matrix(runif(1000000),nrow=1000)
Rprof()
inefficientFn(mymat)
Rprof(NULL)
summaryRprof()
inefficientFn
inefficientFn<- function(x)
{
tmp <- 0
for (i in 1:nrow(x))
{
b <- exp(1/1:ncol(x))
tmp <- tmp + x[i,] * b
}
sum(tmp)
}
$by.total
total.time total.pct self.time self.pct
inefficientFn 0.14 100.0 0.06 42.9
exp 0.06 42.9 0.06 42.9
* 0.02 14.3 0.02 14.3
$sampling.time
[1] 0.14
R.M. Ripley (University of Oxford) Debugging R Functions 2012/13 25 / 29
Checking and Improving your functions Profiling
moreEfficientFn
moreEfficientFn<- function(x)
{
tmp <- 0
b <- exp(1/1:ncol(x))
for (i in 1:nrow(x))
{
tmp <- tmp + x[i,] * b
}
sum(tmp)
}
summaryRprof output
$by.self
self.time self.pct total.time total.pct
moreEfficientFn 0.04 100 0.04 100
$by.total
total.time total.pct self.time self.pct
moreEfficientFn 0.04 100 0.00 100
$sampling.time
[1] 0.04
Profiling: timings
system.time(moreEfficientFn(mymat))
user system elapsed
0.06 0.00 0.07
Exercises