I need to create additional name for my_function(i,x) (where i
can be an integer from 1 to 25). I'd like it to work like this
One way to do achieve this would be:
my_function1 <- function (x) my_function(1, x)
my_function2 <- function (x) my_function(2, x)
my_function3 <- function (x) my_function(3, x)
...
But since there are 25 of them it would be reasonable to make it in a loop. For this I've tried:
for(i in 1:25){
assign(paste("my_function",i,sep=""),function(x) my_function(i,x))
}
but it doesn't work since i
is passed by reference and in the end the result was
How can I pass "i" by value? Or perhaps there is some other way...
Why would I want to do this? I'm improving someones else R package in terms of efficiency but at the same time I need it to be compatible with old version.
This is called currying, and is a part of functional programming.
library(functional)
myf <- function(a,x) cat(a,x,"\n")
myf1 <- Curry(myf, a=1)
myf1(5)
for(i in seq(25)) assign(paste0("myf",i), Curry(myf,a=i) )
> myf15(5)
15 5
I guess there's an important question here as to why you'd want to do this. This seems like exactly the kind of thing you'd want arguments not many related functions for.
Well, you can achieve the same result, using base
functions too.
The trick is to force (force
) the evaluation of i
at each iteration and assign your function in the .Globalenv
(or the environment you like)
my_function <- function(a, b) a + b
lapply(1:10, function(i) {
force(i)
assign(paste0("my_function", i), function(x) my_function(i, x), envir = .GlobalEnv)
}
)
my_function1(10)
## [1] 11
my_function9(10)
## [1] 19
I think bquote
will help here:
for(i in 1:2){
assign(paste("my_function",i,sep=""), bquote( function(x) my_function( i = .(i) , x ) ) )
}
>my_function2
# function(x) my_function(i = 2L, x)
But the point still stands - why would you want to do this?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With