首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >R -nested循环

R -nested循环
EN

Stack Overflow用户
提问于 2019-06-05 01:56:20
回答 1查看 89关注 0票数 0

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

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

代码语言:javascript
复制
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的新手,不知道如何改进我的代码。任何帮助都是非常感谢的。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-06-05 12:51:16

数据(OP)

代码语言:javascript
复制
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传递给函数

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

代码语言:javascript
复制
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))

将参数和结果绑定到一个很好的摘要中:

代码语言:javascript
复制
summary <- bind_cols(params, result)

让我们来看看结果:

代码语言:javascript
复制
    > 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

我们可以选择一个特定的类型,如下所示:

代码语言:javascript
复制
summary %>%
  filter(trial == 8, n == 2, q == 0.5) %>%
  .$matrix %>% 
  .[[1]]

在我的机器上,microbenchmark::microbenchmark报告的运行时间大约是7ms,但这是我的“虚拟”函数。希望你的函数也能运行的很快。祝好运。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56449089

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档