簡體   English   中英

在 R 替代方案中使用嵌套循環

[英]Using a nested loop in R alternative

我在 R 中有以下代碼,我正在嘗試加快速度,因為我知道 R 中的循環較慢。有沒有辦法在不必使用嵌套循環的情況下執行此 R。

# initialize 2 vectors of length 10,000
totalNum <- rep(0,10000)
totalAmt <- rep(0,10000) 
values <- sample(200:5000,150000, replace = TRUE)
chances <-  # similar to f in length and contains values between 0 and 1 

# loop over length of a vector 
 for (i in 1:150000){
   # value between 200-5000 
   value <- values[i]
   # value of number between 0 and 1 
   chance <- chances[i]

  # loop over vectors created 
  for (j in 1:10000){
    # run test 
    dice <- runif(1)
    if (dice < chance){

    totalnum[j] <-  totalNum[j] + 1
    totalAmt[j] <- totalAmt[j] + value
   }

  }

}

我一直在嘗試使用 lapply 或 mapply 但它似乎不適用於這種情況。

值和機會向量的size = 150000

library('data.table')
df1 <- data.table(totalNum = rep(0,10000),
                  totalAmt = rep(0,10000))
values <- sample(200:5000,150000, replace = TRUE)
chances <-  runif(n=150000, min=1e-12, max=.9999999999)

invisible( mapply( function(value, chance){
  df1[runif(10000) < chance, `:=` (totalNum = totalNum + 1, totalAmt = totalAmt + value)]
  return(0)
}, value = values, chance = chances) )

在我的系統上,此代碼使用system.time()函數在以下時間完成。

# user  system elapsed 
# 252.83   43.93  298.68 

lapplymapply只是隱藏循環,對for循環進行了邊際改進。 為了顯着改進,您需要使用函數的矢量化形式。

內部循環很容易用矢量化形式替換:

#generate all of the rolls
dice<-runif(10000)

#identify the affected index
dicelesschance<-which(dice<chance)

#update the values 
totalNum[dicelesschance]<-totalNum[dicelesschance] + 1
totalAmt[dicelesschance]<-totalAmt[dicelesschance] + value

這應該對性能有明顯的改進。

暫無
暫無

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

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