Building on hrbrmstr's answer, here is an easy-to-use wrapper, without using external packages.
The function used to patch other functions.
patch.function <- function(fun, patch, position = 1) {
# Deparse the body.
fun.body <- deparse(body(fun))
# Append the patch to function body where intended.
patched.fun.body <- paste0(
c(fun.body[1:position], patch, fun.body[(position + 1):length(fun.body)]),
collapse = "\n"
)
# Parse and treat as an expression.
expr <- as.expression(parse(text = patched.fun.body))
return(expr)
}
Let's say we want to patch the following dummy function.
dummy.fun <- function() {
print("- a line A of the function body.")
print("- a line B of the function body.")
print("- a line C of the function body.")
print("- a line D of the function body.")
print("- a line E of the function body.")
print("- a line F of the function body.")
print("- a line G of the function body.")
print("- a line H of the function body.")
}
We can use it as:
body(dummy.fun) <- patch.function(dummy.fun, "print('Before the A line of the body.')")
dummy.fun()
# Output:
# [1] "Before the A line of the body."
# [1] "- a line A of the function body."
# [1] "- a line B of the function body."
# [1] "- a line C of the function body."
# [1] "- a line D of the function body."
# [1] "- a line E of the function body."
# [1] "- a line F of the function body."
# [1] "- a line G of the function body."
# [1] "- a line H of the function body."
body(dummy.fun) <- patch.function(dummy.fun, "print('Before the D line of the body.')", position = 5)
dummy.fun()
# Output:
# [1] "Before the A line of the body."
# [1] "- a line A of the function body."
# [1] "- a line B of the function body."
# [1] "- a line C of the function body."
# [1] "Before the D line of the body."
# [1] "- a line D of the function body."
# [1] "- a line E of the function body."
# [1] "- a line F of the function body."
# [1] "- a line G of the function body."
# [1] "- a line H of the function body."