试图用大型数据集的apply函数替换R中的for循环

试图用大型数据集的apply函数替换R中的for循环,r,loops,apply,lapply,replicate,R,Loops,Apply,Lapply,Replicate,我试图对大量参数组合执行一个简单的计算。我有15625个排列,希望对每个组合进行蒙特卡罗实验(~5000)。我的问题是正确地存储数据并避免循环,因为循环会花费很长时间。我想使用apply函数,但无法理解它们。我有下面的代码,它可以运行,但是效率很低!我对保存“res[I,j]”值感兴趣。我已经看到一种简单的蒙特卡罗方法是使用replicate命令……但显然我还没有做到。。。。 任何建议都将不胜感激 #run the beta function beta <- function(M) {

我试图对大量参数组合执行一个简单的计算。我有15625个排列,希望对每个组合进行蒙特卡罗实验(~5000)。我的问题是正确地存储数据并避免循环,因为循环会花费很长时间。我想使用apply函数,但无法理解它们。我有下面的代码,它可以运行,但是效率很低!我对保存“res[I,j]”值感兴趣。我已经看到一种简单的蒙特卡罗方法是使用replicate命令……但显然我还没有做到。。。。 任何建议都将不胜感激

#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
    }

  }

}
#运行beta函数

beta只需移除for j循环即可。它似乎没有任何作用

似乎您可以一起摆脱内部循环,因为我在该循环中没有看到任何依赖于
j
,除非您将值添加到数据帧中。最后一部分可以重写为
res[i,]