Change the body text of existing function objects

I have some .Rdata files containing stored functions as defined by approxfun ().

Some of the save files precede a change in the approximation from the base “base” to “statistics”, and therefore the body has

PACKAGE = "base" 

and the wrong packet causes the function to fail. I can fix (myfun) and just replace "base" with "stats", but I want a neat automatic way.

Can this be done with gsub () and body ()?

I can get the body text and replace it

 as.character(body(myfun)) 

but I don’t know how to put this back in the “call” and replace the definition.

(I know the best solution is to save the data originally used by the application and just recreate the function, but I wonder if there is a reasonable way to modify the existing one.)

Edit: I found it here

What are the ways to edit a function in R?

+7
r
source share
1 answer

Use the substitute function.

For example:

 myfun <- function(x,y) { result <- list(x+y,x*y) return(result) } 

Using body , consider myfun as a list to choose what you would like to change in the function:

 > body(myfun)[[2]][[3]][[2]] x + y 

When changing this parameter, you must use the substitute function to replace part of the function with a call or name object, if necessary. Replacing character strings does not work, because functions are not stored or used as character strings.

 body(myfun)[[2]][[3]][[2]] <- substitute(2*x) 

Now the selected fragment of the function has been replaced:

 > myfun function (x, y) { result <- list(2 * x, x * y) return(result) } 
+3
source share

All Articles