本文介绍了R:在循环中定义函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在循环中定义多个功能:
Defining multiple functions in a loop:
par <- 1:2 #parameters for functions
qF <- list() #list I will write the functions into
for(i in 1:2){
qF[[i]] <- function(p){qnorm(p, mean = par[i])}
}
我的结果:
>qF
[[1]]
function (p)
{
qnorm(p, mean = par[i])
}
[[2]]
function (p)
{
qnorm(p, mean = par[i])
}
功能相同!我想要的结果是:
The functions are the same! What I WANT my result to be:
>qF
[[1]]
function (p)
{
qnorm(p, mean = par[1])
}
[[2]]
function (p)
{
qnorm(p, mean = par[2])
}
有什么办法吗?
推荐答案
如果要动态创建函数,则需要每次对 par [i]
进行评估,否则需要对所有 par [i] ,而 i
将是循环结束时的值.
If you want to create the functions dynamically you need for the par[i]
to evaluate each time, otherwise all the par[i]
will be evaluated when the functions are called, and i
will be the value at the end of the loop.
for(i in 1:2){
qF[[i]] <- local({
mu <- par[i]
function(...) { qnorm(..., mean = mu) }
})
}
您还可以将变量替换
到函数主体中
You could also substitute
the variable into the function body
for(i in 1:2){
qF[[i]] <- eval(substitute(
function(...) qnorm(..., mean = mu)), list(mu=par[i]))
}
您会看到每个函数环境中的 mu
是什么
And you can see what mu
is in each function's environment
sapply(qF, function(f) mget("mu", environment(f)))
# $mu
# [1] 1
#
# $mu
# [1] 2
这篇关于R:在循环中定义函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!