R 嵌套循环

R -nested loops

我正在尝试编写代码来模拟大小为 4*16*10 的 3D 数组,其中每个单元格包含 10*10 矩阵

到目前为止,我确实嵌套了 for 循环,但它们非常慢。我想用 apply 或 mapply 函数替换它们。

M=10
N=10
c=2
n=seq(1, 4, by=1)
p=0.25
q=seq(1,0.25, by =-0.05)
ntrials = 10




for (i in 1:length(n)){
  for (j in 1:length(q)){
    for (k in 1:ntrials){
      plant_subm=matrix_plantsubm(M,N,c,n,p,q)

}
}
}

这里matrix_plantsubm是生成10*10矩阵的函数。我需要为 n 和 q 的每个选择获取矩阵并重复 10 次。

我是 R 的新手,不知道如何改进我的代码。 感谢任何帮助。

数据(OP)

M=10
N=10
c=2
n=seq(1, 4, by=1)
p=0.25
q=seq(1,0.25, by =-0.05)
ntrials = 10

创建参数,通过pmap

传递给函数

这将创建您需要的所有值组合

params <- expand.grid(
  trial = 1:10,
  M = M,
  N = N,
  c = c,
  n = n,
  p = p,
  q = q
) %>%
  as_tibble()

View(params)

# > nrow(params)
# [1] 640

# replace with your own, of course
my_madeup_function <-
  function(M, N, c, n, p, q) {
    matrix(data = rep(M * N + c - n * p * q, 100),
           nrow = 10,
           ncol = 10)
  }

# we use `purrr::pmap`, an apply-type function to pass all of the parameters (except for trials) to the function:

result <- tibble(matrix = pmap(select(params, -trial), my_madeup_function))

将参数和结果绑定在一个很好的总结中:

summary <- bind_cols(params, result)

我们来看看结果:

    > summary
# A tibble: 640 x 8
   trial     M     N     c     n     p     q matrix              
   <int> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <list>              
 1     1    10    10     2     1  0.25     1 <dbl[,10] [10 x 10]>
 2     2    10    10     2     1  0.25     1 <dbl[,10] [10 x 10]>
 3     3    10    10     2     1  0.25     1 <dbl[,10] [10 x 10]>
 4     4    10    10     2     1  0.25     1 <dbl[,10] [10 x 10]>
 5     5    10    10     2     1  0.25     1 <dbl[,10] [10 x 10]>
 6     6    10    10     2     1  0.25     1 <dbl[,10] [10 x 10]>
 7     7    10    10     2     1  0.25     1 <dbl[,10] [10 x 10]>
 8     8    10    10     2     1  0.25     1 <dbl[,10] [10 x 10]>
 9     9    10    10     2     1  0.25     1 <dbl[,10] [10 x 10]>
10    10    10    10     2     1  0.25     1 <dbl[,10] [10 x 10]>
# ... with 630 more rows

我们可以 select 一个特定的,例如:

summary %>%
  filter(trial == 8, n == 2, q == 0.5) %>%
  .$matrix %>% 
  .[[1]]

在我的机器上,microbenchmark::microbenchmark 报告了大约 7 毫秒的 运行 时间,但这是我的 "dummy" 函数。希望您的功能 运行 也很快。祝你好运。