【问题标题】:List of functions as parameter of function (R)作为函数参数的函数列表 (R)
【发布时间】:2023-01-22 07:52:27
【问题描述】:

我有一个问题:我需要在另一个函数中一遍又一遍地运行相同的函数,但参数不同。我如何直接实现它,因为我目前正在执行的手动方法会产生非常多的代码并使我的代码不可读?

伪代码:

internal_func <- function(x, y, z)

external_func <- function(list_of_functions) {
   # do some stuff

   for(i in 1:length(list_of_functions)){
      # evaluate the internal function and save the results in a matrix
   }

   # do some more stuff
   return(stuff)
}

# run 1
# generate list of internal_func with varying x and pass it to external_func

# run 2
# generate list of internal_func with varying y and pass it to external_func

# run 3
# generate list of internal_func with varying y and pass it to external_func

先感谢您!

【问题讨论】:

  • (1) 强烈推荐seq_along(list_of_functions)而不是1:length(.),在list_of_functions为空的情况下更安全/防御。 (2) 假设像list_of_functions &lt;- list(min, mean, max)这样的东西安全吗? (3) 我不知道这一切是如何联系在一起的,也许您可​​以为此添加一些内容并使其可重现?

标签: r functional-programming


【解决方案1】:

只是猜测什么对你有用;发现很难从你的伪代码中猜测...... 无论如何,这里有一些小代码可以生成一个函数列表,每个函数都有不同的参数(这会改变它们将生成的数字数量);这些被传递给一个对其结果进行操作的外部函数


library(purrr)

my_partials <- map(1:5,(x_)
    partial(.f=rnorm,n=x_))

outerfunc <- function(func){
  round(func(),0)
}
map(my_partials,outerfunc)
[[1]]
[1] 1

[[2]]
[1]  1 -1

[[3]]
[1] 0 0 0

[[4]]
[1]  1  0  0 -1

[[5]]
[1] -1  2  1  1  0

【讨论】: