Reputation: 683
I would like to generate a list of functions in R. Basically, I'd like to generate a list of functions of the form f <- function(x){a*x}
where I specify a vector of a
values. Is this possible?
Or is it possible to specify a value of a
and then have R interpret the function with a
evaluated already? To clarify, if I specify a <- 2
, can I make R think of f
as function(x){2*x}
instead of function(x){a*x}
?
Upvotes: 1
Views: 199
Reputation: 683
Here's another solution, which I tried but thought had failed. We can use a closure, which is a function that returns a function.
cl <- function(a){
f <- function(x){a*x}
return(f)
}
cl(1)(1)
cl(5)(1)
Upvotes: 0
Reputation: 99341
Something like this may also be handy. You can alter the body of a function with body
and get
> f <- function(x) a*x
> f
function(x) a*x
> a <- 2
> body(f)[[2]] <- get('a')
> f
function (x)
2 * x
> f(1:5)
# [1] 2 4 6 8 10
The body of a function is a list, and it's elements can be accessed just like any other list.
> body(f)
2 * x
> as.list(body(f))
# [[1]]
# `*`
# [[2]]
# [1] 2
# [[3]]
# x
Upvotes: 2
Reputation: 206263
Yes you can do that. Here's an example
a<-1:5
fn<-lapply(a, function(i) {
force(i)
function(x) {
x * i
}
})
fn[[1]](1)
fn[[5]](1)
The only "trick" here is the force()
function. Because R uses lazy evaluation, it doesn't decode the i
value until you actually need it. If you don't put the force
in there, when you go to use a function, it will finally resolve i
and i
will just be the last value it was in the lapply
which is 5
in this case.
Upvotes: 4