我有两个函数嵌套在另一个函数中,我希望父函数中声明的参数传递给子函数(只有当参数与函数相关时)。
# child function 1
child_f1 <- function(x1 = 1, x2 = 3) {
res <- x1^2 + 4 * x2
}
# child function 2
child_f2 <- function(z = 2) {
res <- z * 1.345
}
# parent function
parent_f <- function(y = 4, ...) {
res <- (child_f1(...) ^ y) + child_f2(...)
# print(res)
return(res)
}
测试如下:
parent_f(y = 2, x1 = 2, x2 = 0, z = 3)
# Error in child_f1(...) (from #2) : unused argument (z = 3)
# Expected result:
(((2)^2 + 4*(0)) ^ (2)) + (3) * 1.345
[1] 20.04
如何告诉child_f1
只能使用x1
和x2
(如果可用,否则使用默认值),child_f2
只能使用z
(如果可用,否则使用默认值)?
我希望坚持使用...
,而不是使用声明的所有可能参数重写parent_f()
。
3条答案
按热度按时间qv7cva1a1#
向每个子节点添加...以获取未使用的参数。parent_f不变。
如果您无法修改子对象或父对象,请使用以下命令:
cuxqih212#
我们可以使用
formals
将参数减少到子函数所支持的参数,这依赖于所有被命名的参数,这在这里是受支持的,之后,我们使用do.call
以编程方式调用一个带有参数列表的函数。i2loujxw3#
你可以利用
formal
并根据你的使用情况设计一个合适的函数