ran*_*tic 4 arguments r function
我正在编写一个 R 函数,例如 foo()。我希望能够传入参数的名称和值以在 foo() 内的函数中进行计算。例如:
foo = function(inputArg, inputVal){
return( rnorm(100, inputArg=inputVal) )
}
Run Code Online (Sandbox Code Playgroud)
然后,我可以评估
foo("sd", 2)
Run Code Online (Sandbox Code Playgroud)
并获得一个由 100 个随机正态值组成的向量,标准差等于 2。我该怎么做?
对于这种情况,最好使用允许do.call您以列表形式传递所有参数的语法。例如
foo = function(inputArg, inputVal){
args <- list(100, inputVal)
names(args) <- c("", inputArg)
do.call(rnorm, args)
}
Run Code Online (Sandbox Code Playgroud)
我们可以按照您的期望来称呼它。
foo("sd", 2)
Run Code Online (Sandbox Code Playgroud)
这args只是一个常规列表,其中每个元素对应于您将作为参数传递的值。如果您想要命名参数,则可以设置列表的名称。如果要将参数保留为位置参数(未命名),请将其名称设置为""。