Is there a way to add a pre-hook in R?

38 views Asked by At

The function addTaskCallback() allows you to add some custom code that will run after other code (example).

Is there a way in R of achieving the opposite, that is, to add some code that will run before other code?

What I know so far

I know I could edit the actual script, but I'd prefer to create a call back that runs before other code (sometimes known as a 'pre-hook', or 'before hook'.

1

There are 1 answers

0
user2554330 On

You can do that if you write your own front end. It doesn't need to be a full front end like RStudio, simply something to collect inputs and evaluate them.

For example, if you want to do this on source code from a file, this is the sort of thing you could do:

sourceWithHooks <- function(filename, prehook = NULL, posthook = NULL, envir = parent.frame(), ...) {
  exprs <- parse(filename)
  for (i in seq_along(exprs)) {
    expr <- exprs[[i]]
    if (is.function(prehook))
      prehook(expr, envir)
    res <- withVisible(eval(expr, envir = envir, ...))
    if (is.function(posthook))
      posthook(expr, res, envir)
  }
} 

prehook <- function(expr, envir) {
  cat(deparse(expr), "\n")
}

posthook <- function(expr, res, envir) {
  if (res$visible)
    print(res$value)
}

sourceWithHooks(somefile, prehook = prehook, posthook = posthook)

This doesn't do anything very fancy but it's the basic outline.