簡體   English   中英

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

我們可以通過以下方式選擇特定的:

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

在我的機器上, microbenchmark::microbenchmark報告的運行時間大約為7毫秒,但這是我的“虛擬”功能。 希望你的功能也能快速運行。 祝好運。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM