How to disable several functions

If I have several interconnected functions, it is useful to trace the path through them. It uses a function traceto give a message every time R enters or exits one of the functions. For instance,

f <- function() g()
g <- function() h()
h <- function()
{
 if(runif(1) > 0.3) g() else 99
}

trace_my_fns <- function()
{
  fn_names <- c("f", "g", "h")
  invisible(trace(
    fn_names,
    tracer = quote(0),
    exit   = quote(0),
    where  = globalenv()
  ))
}

trace_my_fns()
set.seed(4)
f()

When I finished this trace, I need to skip them.

untrace_my_fns <- function()
{
  fn_names <- c("f", "g", "h")
  invisible(trace(
    fn_names,
    where = globalenv()
  ))
}
untrace_my_fns()

For some reason, this does not require the functions to work properly. To see this, take a look at

f
body(f)

If I directly call untrace for each function, for example untrace(f)on the commmand line, it works. How do I create a function to immediately disable all my functions?

+3
source share
1 answer

Well, change to:

untrace_my_fns <- function()
{
  fn_names <- c("f", "g", "h")
  invisible(untrace(
    fn_names,
    where = globalenv()
  ))
}

untrace_my_fns()
set.seed(4)
f() # no more tracing...

... because you called traceinstead untrace!

+6
source

All Articles