cryptomanic cryptomanic - 1 month ago 5
R Question

Modify functions in R using body, formals and environment methods

function definition

f <- function(x) {
x + x*x
}


3 methods i.e.
body
,
formals
and
environment
can be used for modification

body

> body(f)
{
x + x * x
}


If we want to change the body using
body


> body(f) <- expression({x*x*x})
> f
function (x)
{
x * x * x
}


see its changed.

formals

If want to change the arguments using
formals
to
(x = 3, y = 6)


> formals(f) <- list(x = 3, y = 4)
> f
function (x = 3, y = 4)
{
x * x * x
}


see its changed.

But if want to change the arguments to
(x, y)
instead. Obviously
formals(f) <- list(x, y)
will not work.

Any help will be appreciated.

Answer

You need to use alist:

formals(f) = alist(x =, y =)

alist constructs a list from its unevaluated arguments.