如果未在包装器函数中指定,如何使父函数默认运行
我正在编写一个包装函数,其中我正在链接管道的多个步骤。我想将其做到,以便用户可以输入多个选项,如果存在该值,则可以输入该值,而Paernt的默认功能否则。
例如
orig_func1 <- function(num = 1, x=3, y=2){
num <- (x + y)/num
return(num)
orig_func2 <- function(num = 1, z=5, w=23){
num <- (z - w)/num
return(num)
,现在我想创建一个包装器,以执行指定的次数。 每次迭代作为下一个功能的输入进行更改
wrapper <- function(
num = 1,
steps = list(c(step = NULL, x = NULL, y = NULL),
c(...),...){
for (i in 1:length(steps)){
if (steps[[i]]['step'] == "orig_func1"){
num <- orig_func1(num = num, x = steps[[i]][['x']], y = steps[[i]][['y']]
}
if (steps[[i]]['step'] == "orig_func2"){
num <- orig_func2(num = num, z = steps[[i]][['z']], y = steps[[i]][['z']]
}
}
NUM使用
test <- (
num = 1,
steps = list(c(step = orig_func1, x = 2, y = 5),
c(step = orig_func2, z = 4, w = 6),
c(step = orig_func1, x = 2) # I want default for y in this case
我希望 [[i]] [['y']]找不到。我该如何制作它,以便如果不在包装器中的默认值重新确定默认值中,则使用父函数的默认值?
I am writing a wrapper function where I am linking multiple steps of a pipeline. I would like to make it so the user can input multiple options where the value would be input if present, and the default of the paernt function otherwise.
For example
orig_func1 <- function(num = 1, x=3, y=2){
num <- (x + y)/num
return(num)
orig_func2 <- function(num = 1, z=5, w=23){
num <- (z - w)/num
return(num)
now I want to create a wrapper to perform each of these a specified amount of times. I want num to change with each iteration as an input for the next function
wrapper <- function(
num = 1,
steps = list(c(step = NULL, x = NULL, y = NULL),
c(...),...){
for (i in 1:length(steps)){
if (steps[[i]]['step'] == "orig_func1"){
num <- orig_func1(num = num, x = steps[[i]][['x']], y = steps[[i]][['y']]
}
if (steps[[i]]['step'] == "orig_func2"){
num <- orig_func2(num = num, z = steps[[i]][['z']], y = steps[[i]][['z']]
}
}
If for example I tried to run this
test <- (
num = 1,
steps = list(c(step = orig_func1, x = 2, y = 5),
c(step = orig_func2, z = 4, w = 6),
c(step = orig_func1, x = 2) # I want default for y in this case
Lets say I try to run this while leaving y blank for the third step because I want default, this would throw an error because steps[[i]][['y']] wont be found. How can I make it so the default of the parent function is used if not present in the step list without respecifiying the defaults in the wrapper?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的代码并不特别清楚,并且存在许多错误,因此很难确切地看到您要做的事情 - 例如,您不会在任何地方返回计算的数字,因此包装器功能的输出始终是无效的。
我认为您可以通过使用
base :: do.call
将参数作为列表提供而不是单独提取它们来解决您要做的事情。这样的事情:
Your code isn't particularly clear and has many errors so it is hard to see exactly what you're trying to do - for example you aren't returning the numbers you calculate anywhere so the output of your wrapper function will always be NULL.
I think what you're trying to do can be solved by using
base::do.call
to supply the arguments as a list rather than individually extracting them as you've done.Something like this: