【问题标题】:Trying to replace for loops in R with apply functions for large dataset尝试用大型数据集的应用函数替换 R 中的 for 循环
【发布时间】:2014-04-09 18:30:01
【问题描述】:

我正在尝试对大量参数组合执行简单的计算。我有 15,625 个排列,并且想为每个组合运行蒙特卡洛实验(~5000)。我的问题是正确存储数据并避免永远占用的 for 循环。我想使用应用功能,但无法弄清楚。我有以下代码,它可以运行,但效率很低!我有兴趣保存“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
    }

  }

}

【问题讨论】:

  • 看来您可以完全摆脱内部循环,因为我在该循环中看不到任何依赖于j 的内容,除非您将值添加到数据框。最后一部分可以重写为res[i,] &lt;- ...。价值回收将负责将价值添加到每一列。

标签: r loops apply lapply replicate


【解决方案1】:

只需删除 for j 循环。它似乎没有任何用处

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-01
    • 1970-01-01
    • 2020-05-07
    • 2021-10-19
    • 1970-01-01
    • 2010-12-03
    相关资源
    最近更新 更多