且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

R:深拷贝一个函数参数

更新时间:2022-12-14 12:47:48

这可以通过在创建函数后手动为形参 j 分配默认表达式来完成:

This can be done by assigning the default expression for the formal parameter j manually, after creating the function:

i <- 3;
f <- function(x,j) x*j;
f;
## function(x,j) x*j
formals(f);
## $x
##
##
## $j
##
##
formals(f)$j <- i;
f;
## function (x, j = 3)
## x * j
formals(f);
## $x
##
##
## $j
## [1] 3
##
i <- 4;
f(4);
## [1] 12

这是唯一可能的,因为 R 是一种很棒的语言,它为您提供对函数的所有三个特殊属性的完全读/写访问,它们是:

This is only possible because R is an awesome language and provides you complete read/write access to all three special properties of functions, which are:

  1. 包含 body 的解析树:body().
  2. 形式参数及其默认值(它们本身就是解析树):formals().
  3. 封闭环境(用于实现闭包):环境()代码>.