Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify functions in R using body, formals and environment methods

Tags:

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.

like image 776
cryptomanic Avatar asked Oct 30 '16 17:10

cryptomanic


1 Answers

You need to use alist:

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

alist constructs a list from its unevaluated arguments.

like image 150
Konrad Rudolph Avatar answered Oct 22 '22 09:10

Konrad Rudolph