Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

modify the body text of existing function objects

Tags:

r

I have some .Rdata files that contain saved functions as defined by approxfun().

Some of the save files pre-date the change to approxfun from package "base" to "stats", and so the body has

PACKAGE = "base"

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

Can I do this with gsub() and body() somehow?

I can get the body text and substitute there with

as.character(body(myfun))

but I don't know how to turn that back into a "call" and replace the definition.

(I know that a better solution is to have saved the data originally used by approxfun and simply recreate the function, but I wonder if there's a sensible way to modify the existing one.)

Edit: I found it here

What ways are there to edit a function in R?

like image 418
mdsumner Avatar asked Jun 04 '10 03:06

mdsumner


1 Answers

Use the substitute function.

For example:

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

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

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

When you change this, you must use the substitute function so you replace the part of the function with a call or name object, as appropriate. Replacing with character strings doesn't work since functions are not stored as or operated on as character strings.

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

Now the selected piece of the function has been replaced:

> myfun
function (x, y) 
{
    result <- list(2 * x, x * y)
    return(result)
}
like image 165
Will Beason Avatar answered Oct 13 '22 11:10

Will Beason