R:深拷贝一个函数参数 [英] R: deep copy a function argument
问题描述
考虑下面的代码
i = 3
j = i
i = 4 # j != i
然而,我想要的是
i = 3
f <- function(x, j=i)
x * j
i = 4
f(4) # 16, but i want it to be 12
如果您想知道我为什么要这样做,您可以考虑这段代码 - 该应用程序是一个多递减模型.转换矩阵的对角线是该行中其他减量的总和.我想定义我需要的减量,而不是使用这些减量计算其他函数.在这种情况下,我只需要 uxt01 和 uxt10,我想从中生成函数 uxt00 和 uxt11.我想要一些可以扩展到更高维度的东西.
In case you are wondering why I want to do this you could consider this code - the application is a multiple decrements model. The diagonals of a transition matrix are the sum of the other decrements in that row. I would like to define the decrements I need than calculate the other functions using those decrements. In this case, I only need uxt01 and uxt10 and from these I want to produce the functions uxt00 and uxt11. I wanted something that scales to higher dimensions.
Qxt <- matrix(c(uxt00=function(t=0,x=0) 0,
uxt01=function(t=0,x=0) 0.05,
uxt10=function(t=0,x=0) 0.07
uxt11=function(t=0,x=0) 0), 2, 2, byrow=TRUE)
Qxt.diag <- function(Qxt) {
ndecrements <- length(Qxt[1,])
for(index in seq(1, N, N+1)) { # 1, 4
Qxt[[index]] <- function(t=0, x=0, i=index, N=ndecrements) {
row <- ceiling(index/ndecr)
row.decrements <- seq( (row - 1)*N + 1, (row)*N)
other.decrements <- row.decrements[which(row.decrements != i]
-sum(unlist(lapply(Qxt.fns[[other.decrements]],
function(f) f(t,x))))
}
}
Qxt.fns
}
推荐答案
这可以通过在创建函数后手动为形参 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:
- 包含 body 的解析树:
body()
. - 形式参数及其默认值(它们本身就是解析树):
formals()
. - 封闭环境(用于实现闭包):<代码>环境()代码>.
这篇关于R:深拷贝一个函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!