簡體   English   中英

嘗試使用適用於大型數據集的函數替換R中的循環

[英]Trying to replace for loops in R with apply functions for large dataset

我正在嘗試對大量參數組合執行簡單的計算。 我有15625個排列,並希望針對每個組合運行蒙特卡洛實驗(〜5000)。 我的問題是正確存儲數據,並避免永久使用循環。 我想使用apply函數,但無法弄清楚它們。 我有以下代碼,可以運行,但是效率很低! 我有興趣保存“ res [i,j]”值。 我已經看到一種簡單的蒙特卡洛方法是使用復制命令...但是顯然我還沒有....任何建議將不勝感激!

#run the beta function
beta <- function(M) {
  b_slope <- log(M) / 10
  return (b_slope)
}
#set the experiment conditions for looping through different M, Cv, and q parameter vals
cvVals <- seq(0.1,3.09,0.12)
mVals <- seq(1,2.98,0.08)
qVals <- seq(0.9,0.999,0.004)
mNum <- length(mVals);cvNum <- length(cvVals);qNum<-length(qVals);
total<-mNum*cvNum*qNum

#iterate through time (up to 5000 yrs)
imax<-5000

#Number of experiments
expts<-5

#fill a matrix with each combination of cv, m, q values
df <- data.frame(expand.grid(cv=cvVals, m=mVals, q=qVals))

#set a column in the df to have X_Crit values
df$i<-seq(1:nrow(df))
df$X_crit <- qlnorm(df$q)

#store the results in a df with the dimensions of df by # of experiments
res <- data.frame(nrow=nrow(df), ncol=expts)

for (i in 1:nrow(df)) {

  for (j in 1:ncol(res)) {
    #fill in all the x_critical values for each q
    X_crit <- df$X_crit[i]

    #compute the mean and std dev and flow for all values up to imax
    tempmean <- beta(df$m[i])*seq(0, imax-1)
    tempstd <- df$cv[i]*tempmean
    #generate imax random lognorm variables as error terms 
    err <- rlnorm(imax, 0, 1)
    #compute flow from lognormal quantile function
    flow <- tempmean + tempstd*err

    #store the result which looks for the first exceedance of flow 
    if (sum(flow>X_crit)>0) {
      res[i, j] <-min(which(flow > X_crit))
    } else {
      res[i,j] <- imax
    }

  }

}

只需刪除for j循環。 似乎毫無用處

暫無
暫無

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

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