在函数内部存储函数参数并将其应用于将来在r中使用

SHR*_*ram 2 r function

我有相当复杂的功能,但以下是我想做的简化版本.

假设我将以下函数设置为返回列表,我希望将传递给函数的参数存储为元素之一.

myfun <- function (a, x, y, z, ...){
         out <- a+x+y+z
         arg <- list(x=x,y=y, z=z,...)
         outlist <- list(out=out, arg=arg)
         return(outlist)
         }
Run Code Online (Sandbox Code Playgroud)

这里我将参数存储在函数列表中.存储参数的目的是我可以在其他函数中完全相同地应用它们而无需再次编写它们.只需使用返回的输出数据对象,我们就可以运行函数可重现的方式.

假设我只想改变,a但其他功能的其他应用也是如此.

xy <- myfun(a=4,x=5,y=6,z=9,k=10)
myfun(a=10, xy$arg)
Error in a + x : non-numeric argument to binary operator
myfun(a=6, xy$arg)
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点 ?

编辑:

一些澄清:

myfun参数是动态的 - 意味着可以采用不同的参数 - 例如上例中的K. 它可以是下一次:

xy <- myfun(a=4,x=5,y=6,z=9,k=10, l=13)
Run Code Online (Sandbox Code Playgroud)

我的想法是将所有在一次运行中传递的参数存储为list(arg$outlist),并且list可以在不同的时间存在不同的元素.

Bro*_*ieG 6

你想要Curry你的功能:

> myfun <- function (a, x, y, z, ...) a+x+y+z
> library(functional)
> myfun2 <- Curry(myfun, x=5,y=6,z=9,k=10)
> myfun2(4)
[1] 24         # == 5 + 6 + 9 + 10 + 4
> myfun2(10)
[1] 30         # == 5 + 6 + 9 + 10 + 10
> myfun2(6)
[1] 26         # == 5 + 6 + 9 + 10 + 6
Run Code Online (Sandbox Code Playgroud)

Curry创建一个预先设置了所有指定参数的新函数.然后,您可以使用该新功能.