gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 09:07:13 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com