尽管对此主题有一些疑问(例如this Question),但它们都没有回答我的特定问题(据我所知还是如此)。
假设我有一个取决于很多参数的函数。为了演示,我选择了3个参数:
myfun <- function(x1, x2, x3){
some code containing x1, x2, x3
}
通常,输入参数已包含在中list
:
xlist <- list(x1 = 1, x2= 2, x3 = 3)
我想myfun
使用包含在其中的输入来运行xlist
:
myfun(xlist$x1, xlist$x2, xlist$x3)
但是,这似乎太费力了(由于大量参数)。
因此,我决定修改myfun
:而不是所有输入参数。现在,它将整个列表作为一个输入输入:在我使用的代码的开头,attach
以便使用与上述相同的代码。
myfun2 <- function(xlist){
attach(xlist)
same code as in myfun containing x1, x2, x3
detach(xlist)
}
我认为这将是一个很好的解决方案,但是许多用户建议不要使用attach
。
你怎么看?是否有任何争论喜欢myfun
过myfun2
?
提前致谢。
我认为您最好使用do.call
。do.call
将接受列表并将其转换为参数。
myfun <- function(x1, x2, x3){
x1 + x2 + x3
}
xlist <- list(x1 = 1, x2= 2, x3 = 3)
do.call(myfun, xlist)
这样做的好处是明确了参数的含义,这使得对代码进行推理,维护和调试变得更加容易。
棘手的地方是如果其中xlist
包含的值比函数所需的更多。例如,以下引发错误:
xlist <- list(x1 = 1, x2 = 2, x3 = 3, x4 = 4)
do.call(myfun, xlist)
您可以通过将参数与形式表达式匹配来规避此问题
do.call(myfun, xlist[names(xlist) %in% names(formals(myfun))])
它仍然有点输入,但是如果您要谈论的是10个以上的参数,它仍然比xlist$x1, xlist$x2, xlist$x3
,等容易得多。
LAP也提供了一个有用的解决方案,但是最好with
在呼叫范围之外使用。
with(xlist, myfun(x1, x2, x3))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句