34  R: Debug Function in a Base R or Packages

Debugging functions from Base R or other packages depend on the complexities of those functions, and how the functions call other functions.

34.1 Option 1: Use debug

Code
set.seed(1234)
n = 20
y1 = round(rnorm(n, 16, 4), 2)
g1 = rep("1", length = n)
y2 = round(rnorm(n, 20, 4), 2)
g2 = rep("2", length = n)
DF = data.frame(y = c(y1, y2), Group = c(g1, g2), stringsAsFactors = TRUE)

debug(lm)

fm = lm(y ~ Group, data = DF)

undebug(lm)

34.2 Option 2: Use trace

Code
set.seed(1234)
n = 20
y1 = round(rnorm(n, 16, 4), 2)
g1 = rep("1", length = n)
y2 = round(rnorm(n, 20, 4), 2)
g2 = rep("2", length = n)
DF = data.frame(y = c(y1, y2), Group = c(g1, g2), stringsAsFactors = TRUE)

trace(lm, tracer = browser, at = 10)

fm = lm(y ~ Group, data = DF)

untrace(lm)

34.3 Option 3: Use trace with edit arguments

If the function is a stand-alone funciton, you may create a copy of the function, rename the function and almost evaluate it as your own function.

Code
trace(lm, tracer = browser, edit = TRUE)

untrace(lm)