What ways are there to edit a function in R?

There is a body<- function that lets you assign new content of the function.

body(foo)[[3]] <- substitute(line2 <- 2)
foo
#-----------    
function (x) 
{
    line1 <- x
    line2 <- 2
    line3 <- line1 + line2
    return(line3)
}

(The “{” is body(foo)[[1]] and each line is a successive element of the list. Therefore the second line is the third element in the expression list. The inserted elements need to be unevaluated expressions rather than text.)

There is also a corresponding formals<- function that lets one perform similar surgery on the argument pairlist.

Note: fixInNamespace is probably a better choice than fix if the function will be calling accessory functional resources in a loaded package. When used from the console, both fix will assign results to the .GlobalEnv.

Leave a Comment