Skip to content

Instantly share code, notes, and snippets.

@yjunechoe
Last active October 1, 2021 06:18
Show Gist options
  • Select an option

  • Save yjunechoe/96b25f220c0e8cb0e27ccf0141d1604d to your computer and use it in GitHub Desktop.

Select an option

Save yjunechoe/96b25f220c0e8cb0e27ccf0141d1604d to your computer and use it in GitHub Desktop.
You can do this???
library(ggplot2)
# This retrieves the function body
body(get("compute_group", StatCount))
# This splits the execution sequence as a list
as.list(body(get("compute_group", StatCount)))
# The trace call
trace(
"compute_group", # the method to trace
where = StatCount, # the ggproto object that the method belongs to
at = 8, # the step to trace
tracer = quote({ # the expression to evaluate at that step
cat("> print(bars)\n")
print(bars)
}),
exit = quote(untrace("compute_group", where = StatCount)) # called at the end to have a "traceonce" effect
)
ggplot(mtcars, aes(cyl)) + geom_bar()
# For even more power, `edit = TRUE`
# trace("compute_group", where = StatCount, edit = TRUE)
@yjunechoe
Copy link
Copy Markdown
Author

Multiple tracer exprs at multiple execution steps !!!

If this ends up being wrapped in a function, needs to rm tracer_idx on exit

library(ggplot)

tracer_idx <- 1

# The trace call
trace(
    "compute_group",  # the method to trace
    where = StatCount,  # the ggproto object that the method belongs to
    at = c(5, 8), # the step to trace
    tracer = function() {
        tracer_expr <- list(
            quote(print(x)),
            quote(print(bars))
        )[[tracer_idx]]
        eval(tracer_expr, envir = parent.frame())
        tracer_idx <<- tracer_idx + 1
    },
    exit = quote(untrace("compute_group", where = StatCount)) # called at the end to have a "traceonce" effect
)

ggplot(mtcars, aes(cyl)) + geom_bar()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment