在R中,如何将参数从父函数传递给子函数?

nfg76nw0  于 2023-01-22  发布在  其他
关注(0)|答案(3)|浏览(169)

我有两个函数嵌套在另一个函数中,我希望父函数中声明的参数传递给子函数(只有当参数与函数相关时)。

# 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只能使用x1x2(如果可用,否则使用默认值),child_f2只能使用z(如果可用,否则使用默认值)?
我希望坚持使用...,而不是使用声明的所有可能参数重写parent_f()

qv7cva1a

qv7cva1a1#

向每个子节点添加...以获取未使用的参数。parent_f不变。

child_f1 <- function(x1 = 1, x2 = 3, ...) {
  res <- x1^2 + 4 * x2
}

child_f2 <- function(z = 2, ...) {
  res <- z * 1.345
}

parent_f(y = 2, x1 = 2, x2 = 0, z = 3)
## [1] 20.035

如果您无法修改子对象或父对象,请使用以下命令:

child_f1_orig <- child_f1
child_f1 <- function(x1 = 1, x2 = 3, ...) child_f1_orig(x1 = x1, x2 = x2)

child_f2_orig <- child_f2
child_f2 <- function(z = 2, ...) child_f2_orig(z = z)

parent_f(y = 2, x1 = 2, x2 = 0, z = 3)
## [1] 20.035
cuxqih21

cuxqih212#

我们可以使用formals将参数减少到子函数所支持的参数,这依赖于所有被命名的参数,这在这里是受支持的,之后,我们使用do.call以编程方式调用一个带有参数列表的函数。

# parent function
parent_f <- function(y = 4, ...) {
  dots <- list(...)
  dots1 <- dots[intersect(names(dots), names(formals(child_f1)))]
  dots2 <- dots[intersect(names(dots), names(formals(child_f2)))]
  res <- (do.call(child_f1, dots1) ^ y) + do.call(child_f2, dots2)
  # print(res)
  return(res)
}

parent_f(y = 2, x1 = 2, x2 = 0, z = 3)
# [1] 20.035
i2loujxw

i2loujxw3#

你可以利用formal并根据你的使用情况设计一个合适的函数

use_fun_with_args <- function(fun, ...) {
  dots <- list(...)
  do.call(fun, args = dots[intersect(names(formals(fun)), 
                                     names(dots))])
}

# parent function
parent_f <- function(y = 4, ...) {
  res <- (use_fun_with_args(fun = child_f1, ...) ^ y) + use_fun_with_args(fun = child_f2, ...)
  # print(res)
  return(res)
}
parent_f(y = 2, x1 = 2, x2 = 0, z = 3)
#> [1] 20.035

相关问题