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.
If your formula contains more than one function, press F2 or double-click the formula cell. Position the cursor within the function that you want to modify and click the Insert Function button, or press Shift+F3. The most efficient way to modify simple functions (that is, those with few arguments) is to do so manually.
Select the lines and press the Ctrl+Enter key (or use the Run toolbar button); or. After executing a selection of code, use the Re-Run Previous Region command (or its associated toolbar button) to run the same selection again.
fix allows a function to be edited on the fly. It is a nice tool to make quick changes, perhaps after identifying problems in a function via debug or to insert or remove a call to browser(). (But don't forget to save the new version elsewhere if it will be needed later.)
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With