使用body,formals和environment方法修改R中的函数

cry*_*nic 21 methods arguments r

功能定义

f <- function(x) {
   x + x*x
}
Run Code Online (Sandbox Code Playgroud)

3种方法,即body,formalsenvironment可用于修改

身体

> body(f)
{
    x + x * x
}
Run Code Online (Sandbox Code Playgroud)

如果我们想改变身体使用 body

> body(f) <- expression({x*x*x})
> f
function (x) 
{
    x * x * x
}
Run Code Online (Sandbox Code Playgroud)

看到它改变了.

甲缩醛

如果想使用改变的参数formals(x = 3, y = 6)

> formals(f) <- list(x = 3, y = 4)
> f
function (x = 3, y = 4) 
{
    x * x * x
}
Run Code Online (Sandbox Code Playgroud)

看到它改变了.

但是如果想改变参数(x, y)而不是.显然formals(f) <- list(x, y)不行.

任何帮助将不胜感激.

Kon*_*lph 21

你需要使用alist:

formals(f) = alist(x =, y =)
Run Code Online (Sandbox Code Playgroud)

alist 从未评估的参数构造一个列表.