R: Defining functions inside a loop
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])}
}
My result:
>qF
[[1]]
function (p)
{
qnorm(p, mean = par[i])
}
[[2]]
function (p)
{
qnorm(p, mean = par[i])
}
The functions are the same! I want my result to be as follows:
>qF
[[1]]
function (p)
{
qnorm(p, mean = par[1])
}
[[2]]
function (p)
{
qnorm(p, mean = par[2])
}
Is there a way to do this?
+3
Daniel
source
to share
2 answers
If you want to dynamically create functions, then for par[i]
you need to evaluate every time, otherwise everything par[i]
will be evaluated when calling functions, 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 can also add substitute
this variable to the function body
for(i in 1:2){
qF[[i]] <- eval(substitute(
function(...) qnorm(..., mean = mu)), list(mu=par[i]))
}
And you can see that mu
in each functional environment
sapply(qF, function(f) mget("mu", environment(f)))
# $mu
# [1] 1
#
# $mu
# [1] 2
+2
jenesaisquoi
source
to share
You can do:
library(functional)
funcs = lapply(1:2, function(u) Curry(qnorm, mean=u))
funcs[[1]](0.77)
#[1] 1.738847
funcs[[2]](0.77)
#[1] 2.738847
Or, if you don't appreciate spicy food:
funcs = lapply(1:2, function(u) function(...) qnorm(..., mean=u))
+3
Colonel Beauvel
source
to share