Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 775
Tal Galili Avatar asked Mar 16 '10 20:03

Tal Galili


People also ask

How do you edit functions?

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.

How do I edit code in R studio?

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.

What does fix do in R?

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.)


1 Answers

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.

like image 90
IRTFM Avatar answered Sep 18 '22 16:09

IRTFM