每次运行时使用不同的参数多次运行一个函数

时间:2018-01-14 23:01:51

标签: r

我试图为每次运行使用不同的参数多次运行一个函数。参数由子函数调用,然后子函数的输出在main函数中使用。我一直试图用mapply来做这件事但是没有运气..

我想做的伪代码:

创建一个由8个不同的可能参数组合组成的df,以便在函数中使用:

a <- 1:2
b <- 1:2
c <- 1:2
my.args <- expand.grid(a = a, b = b, c = c)

head(my.args)
  a b c
1 1 1 1
2 2 1 1
3 1 2 1
4 2 2 1
5 1 1 2

创建功能

my.func <- function(a,b,c) {
    my.sub.func <- function(bits = c(0,1,2), times = 1) {
    sample(bits, times, prob = c(a,b,c), replace = TRUE)
    }
 #..... do a bunch of stuff using my.sub.func()

}

使用每一行my.args作为输入参数

运行该函数
mapply (my.func, a = my.args[,1], b = my.args[,2], c = my.args[,3])

这不起作用,我认为这个问题与prob = c(a,b,c)

my.sub.func()的结构有关

1 个答案:

答案 0 :(得分:0)

感谢@alistaire,我得到了它的工作,如上所述我需要实际调用data_[x + y*width_] = problem_definition::initialize(x, y, scale_); 并向my.sub.func函数添加一个变量来存储每个迭代的参数组合。

my.func

目前情况下,这会产生与a <- 1:2 b <- 1:2 c <- 1:2 my.args <- expand.grid(a = a, b = b, c = c) my.func <- function(a,b,c) { ## add a variable to store argument values in triplet <- c(a, b, c) my.sub.func <- function(bits = c(0,1,2), times = 1) { sample(bits, times, prob = triplet, replace = TRUE) } ## actually call the function my.sub.func() #..... do a bunch of stuff using my.sub.func() here } mapply (my.func, my.args[,1], my.args[,2], my.args[,3]) 相同的输出,但我现在可以将其他计算添加到do.call(mapply, c(function(a, b, c){sample(0:2, 1, prob = c(a, b, c))}, my.args))(即my.func),这些计算将包含在#..... do a bunch of other stuff here中。