modify the body text of existing function objects

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?


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)
}
链接地址: http://www.djcxy.com/p/1002.html

上一篇: 将项目移植到OpenGL3

下一篇: 修改现有函数对象的正文文本