7

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?

Community
  • 1
  • 1
mdsumner
  • 29,099
  • 6
  • 83
  • 91
  • possible duplicate of [What ways are there to edit a function in R?](http://stackoverflow.com/questions/2458013/what-ways-are-there-to-edit-a-function-in-r) –  May 11 '14 at 19:09
  • I tried `body(foo) <- gsub("PACKAGE = 'base'", "PACKAGE = 'stats'", body(foo))` for you, but body() doesn't return text so you can't use text manipulation to change it. I verified this with @MrFlick – Hack-R Aug 05 '14 at 15:44
  • 2
    could you then write your own answer so that this post is no longer "unanswered" ? – Karl Forner Sep 05 '14 at 07:57
  • Nah. It's your itch why don't you scratch it,? – mdsumner Sep 05 '14 at 10:02
  • 1
    I didn't ever think passive-aggressive refusing to answer questions would be a thing. – Will Beason Sep 28 '14 at 20:29

1 Answers1

4

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)
}
Will Beason
  • 3,417
  • 2
  • 28
  • 46