r - 委派函数调用的便捷方式

标签 r function function-declaration

我有一系列类似的函数,它们都需要从数据框中提取一些值。像这样的东西:

foo_1 <- function(data, ...) {
  x <- data$x
  y <- data$y

  # some preparatory code common to all foo_X functions

  # .. do some boring stuff with x and y

  # pack and process the result into 'ret'
  return(ret)
}

然后将这些函数作为参数提供给其他函数(让我们称之为“主函数”。我不能修改主函数)。

但是,我希望我可以避免在每个函数中重新编写相同的准备代码。 例如 , 我不想用 data$x而不是将其分配给 x并使用 x因为它使无聊的东西难以阅读。目前,我需要写x <- data$x (等等)在所有 foo_1 , foo_2 ... 职能。这很烦人并且使代码困惑。此外,所有 foo_N 的包装和加工都是通用的。职能。其他准备代码包括变量的缩放或 ID 的正则化。

这样做的优雅和简洁的方式是什么?

一种可能是 attach()数据框(或使用 with() ,正如 Hong 在下面的答案中所建议的那样),但我不知道我的命名空间中还有哪些其他变量:附加数据可以掩盖我在 fun_1 中使用的其他变量.此外,最好是 foo_N函数应该使用显式参数调用,因此更容易看到它们需要什么以及它们在做什么。

我想到的下一个可能性是这样的结构:
foo_generator <- function(number) {

  tocall <- switch(1=foo_1, 2=foo_2, 3=foo_3) # etc.

  function(data, ...) {
    x <- data$x
    y <- data$y
    tocall(x, y, ...)
    # process and pack into ret
    return(ret)
}

foo_1 <- function(x, y, ...) {
  # do some boring stuff
}

然后我可以使用 foo_generator(1)而不是 foo_1作为主函数的参数。

有没有更好或更优雅的方式?我觉得我在这里忽略了一些明显的东西。

最佳答案

你可能想多了。你说准备和打包的代码都是通用的foo_n职能。那么,我假设 # .. do some boring stuff with x and y是每个功能不同的地方。如果是这种情况,那么只需创建一个 prep_and_pack以函数名作为参数的函数,然后传入foo_1 , foo_2等。例如:

prep_and_pack <- function(data, func){
    x <- data$x
    y <- data$y

    # preparatory code here

    xy_output <- func(x, y) # do stuff with x and y

    # code to pack and process into "ret"

    return(ret)
}

现在您可以创建您的foo_nx 做不同事情的函数和 y :

foo_1 <- function(x, y) {
    # .. do some boring stuff with x and y
}

foo_2 <- function(x, y) {
    # .. do some boring stuff with x and y
}

foo_3 <- function(x, y) {
    # .. do some boring stuff with x and y
}

最后,您可以将多个调用传递给 prep_and_pack进入你的主函数,其中foo_1等通过 func 传入争论:

master_func(prep_and_pack(data = df, func = foo_1),
            prep_and_pack(data = df, func = foo_2),
            prep_and_pack(data = df, func = foo_3)
            )

您也可以使用 switchprep_and_pack和/或放弃foo_n功能完全有利于 if-else 条件来处理各种情况,但我认为上面的内容保持干净。

关于r - 委派函数调用的便捷方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56985140/

相关文章:

c++ - 为什么不总是在 C++ 中通过 const 引用传递?

c++ - 为什么删除重载时需要使用声明

c - 在 C 中定义导致错误之前的函数声明

r - 如何在 dplyr 中使用 NSE 来引用一个变量?

python - 读取和绘制从大文件中读取的数据

r - 在 R 中解析嵌套的父子 json

r - 如何使用 xlim 或 ylim 停止 ggrepel 重叠点

matlab - 在将其本地副本传递给 Matlab 中的函数后删除一个巨大的矩阵

c - 为什么程序编译?

c++ - 通过 "pass by value"将一个函数传递给另一个函数