附加函数名称但参数较少

Luk*_*szJ 5 r function assign

我需要为my_function(i,x)创建其他名称(其中i可以是1到25之间的整数).我希望它像这样工作

  • my_function1(x)与my_function(1,x)相同
  • my_function2(x)与my_function(2,x)相同
  • my_function3(x)与my_function(3,x)相同
  • ...
  • my_function25(x)与my_function(25,x)相同

实现这一目标的一种方法是:

my_function1 <- function (x) my_function(1, x)
my_function2 <- function (x) my_function(2, x)
my_function3 <- function (x) my_function(3, x)
...
Run Code Online (Sandbox Code Playgroud)

但是因为它们中有25个,所以在循环中制作它是合理的.为此,我尝试过:

for(i in 1:25){
  assign(paste("my_function",i,sep=""),function(x) my_function(i,x))
}
Run Code Online (Sandbox Code Playgroud)

但它不起作用,因为i通过引用传递,最后结果是

  • my_function1(x)与my_function(25,x)相同
  • my_function2(x)与my_function(25,x)相同
  • my_function3(x)与my_function(25,x)相同
  • ...

我怎样才能通过值传递"i"?或许还有其他方式......

我为什么要这样做?我在效率方面改进了其他R包,但同时我需要它与旧版本兼容.

Ari*_*man 6

这称为currying,是函数式编程的一部分.

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
Run Code Online (Sandbox Code Playgroud)

我想这里有一个重要的问题,为什么你想要这样做.这看起来就像你想要的参数不是很多相关函数.