'What ways are there to edit a function in R?

Let's say we have the following function:

foo <- function(x)
{
    line1 <- x
    line2 <- 0
    line3 <- line1 + line2
    return(line3)
}

And that we want to change the second line to be:

    line2 <- 2

How would you do that?

One way is to use

fix(foo)

And change the function.

Another way is to just write the function again.

Is there another way? (Remember, the task was to change just the second line)

What I would like is for some way to represent the function as a vector of strings (well, characters), then change one of it's values, and then turn it into a function again.



Solution 1:[1]

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.

Solution 2:[2]

fix is the best way that I know of doing this, although you can also use edit and re-assign it:

foo <- edit(foo)

This is what fix does internally. You might want to do this if you wanted to re-assign your changes to a different name.

Solution 3:[3]

fixInNamespace is like fix, for functions in a package (including those that haven't been exported).

Solution 4:[4]

You can use the 'body' function. This function will return the body of function:

fnx = function(a, b) { return(a^2 + 7*a + 9)}
body(fnx)
# returns the body of the function

So a good way to 'edit' a function is to use 'body' on the left-hand side of an assignment statement:

body(fnx) = expression({a^2 + 11*a + 4})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Shane
Solution 3 Richie Cotton
Solution 4 doug