将任意参数传递给R中的多个嵌套函数 [英] Passing arbitrary arguments to multiple nested functions in R
问题描述
找不到与我要执行的操作类似的问题.我有一个主力函数,可以采用任何定制的子函数类及其各自的参数,并对其进行某些处理,例如以下玩具示例:
Can't find a question similar to what I am trying to do. I have a workhorse function that can take any of a class of custom-made sub-functions, with their respective arguments, and do certain processing on it, like the following toy examples:
func1 <- function(a, b, c) {a + b * c}
func2 <- function(x, y, z, bob, bleb) {(x / y)^bleb * z/bob}
workhorse <- function(m, n, o, FUN, ...) {
result <- FUN(x, y, ...)
[process result with m, n, and o]
}
就其本身而言,这可以很好地实现预期的效果,如
By itself, this works perfectly well as intended, as in
foo <- workhorse(m, n, o, func1, a, b, c)
foo2 <- workhorse(m, n, o, func2, x, y, z, bob, bleb)
我正在尝试为工作马(meta_workhorse)创建一个包装器,该包装器将接受一系列功能(按引用的名称)以遍历工作马并组合结果,如下所示.
I am trying to create a wrapper for workhorse (meta_workhorse) that will accept a list of functions (by quoted name) to run through workhorse and combine the results, something like below.
FUN_list <- c('func1', 'func2')
ARGS_list <- list(c(a, b, c), c(x, y, z, bob, bleb))
meta_workhorse <- function(mm, nn, oo, FUN_list, ARGS_list) {
meta_result <- sapply(1:length(FUN_list), function(x) {
workhorse(mm, nn, oo, get(FUN_list[x]), ARGS_list[x], ...)
}
}
问题在于每个子函数采用不同的参数,因此我需要将进入get()函数的函数名称与ARGS_list中的相应参数列表进行链接.我已经尝试了所有我能想到的一切,包括do.calls,设置正式形式(主力),都无济于事.在这种情况下如何传递参数?
The problem is that each of the sub-functions take different arguments, so I need to link the function name going into the get() function with the corresponding list of arguments in ARGS_list. I've tried everything I could think of, including do.calls, setting formals(workhorse), to no avail. How do I pass the arguments in this case?
Nicola的答案解决了大多数问题,但是仍然有一个子函数(使用打包函数)不断给出错误未使用的参数... = list(x,y)".在我浏览以前的省略号问题时正在寻找一些建议.
Nicola's answer solved most of the issue, but still have one subfuction (using a packaged function) keeps giving the error "unused argument ... = list(x, y)". Looking for some suggestions while I dig through previous ellipsis questions.
推荐答案
我想您应该将ARGS_list
声明为列表列表,而不是普通列表.然后,您可以继续使用do.call
.一个例子(希望得到的就是这样):
I guess you should declare your ARGS_list
as a list of lists, instead of a normal list. Then, you can proceed to use do.call
. An example (hoping that is what you are looking for):
func1 <- function(a, b, c) {a + b * c}
func2 <- function(x, y, z, bob, bleb) {(x / y)^bleb * z/bob}
workhorse <- function(m, n, o, FUN, ...) {
result <- FUN(...)
result+m+n*o
}
FUN_list <- c('func1', 'func2')
ARGS_list <- list(list(a=1, b=2, c=3), list(x=4, y=5, z=6, bob=7, bleb=8))
meta_workhorse <- function(mm, nn, oo, FUN_list, ARGS_list) {
sapply(1:length(FUN_list), function(x) {
do.call(workhorse,c(list(m=mm,n=nn,o=oo,FUN=get(FUN_list[x])),ARGS_list[[x]]))
})
}
meta_workhorse(1,2,3,FUN_list,ARGS_list)
# [1] 14.000000 7.143805
这篇关于将任意参数传递给R中的多个嵌套函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!