我创建了以下代码,将 for 循环嵌套在 R 中的 for 循环内。它是计算 Power 的模拟。我读过 R 不适合做 for 循环,但我想知道是否有任何效率可以应用来使这个运行更快一点。我对 R 以及任何类型的编程都很陌生。现在我看到的运行时间是:
m=10 我得到 0.17 秒
m=100 我得到 3.95 秒
m=1000 我得到 246.26 秒
m=2000 我得到 1003.55 秒
我希望将采样次数 m 设置为 100K 以上,但我什至不敢将其设置为 10K
这是代码:
m = 1000 # number of times we are going to take samples
popmean=120 # set population mean at 120
popvar=225 # set known/established population
variance at 225
newvar=144 # variance of new methodology
alpha=.01 # set alpha
teststatvect = matrix(nrow=m,ncol=1) # empty vector to populate with test statistics
power = matrix(nrow=200,ncol=1) # empty vector to populate with power
system.time( # not needed - using to gauge how long this takes
for (n in 1:length(power)) # begin for loop for different sample sizes
for(i in 1:m){ # begin for loop to take "m" samples
y=rnorm(n,popmean,sqrt(newvar)) # sample of size n with mean 120 and var=144
ts=sum((y-popmean)^2/popvar) # calculate test statistic for each sample
teststatvect[i]=ts # loop and populate the vector to hold test statistics
vecpvals=pchisq(teststatvect,n) # calculate the pval of each statistic
power[n]=length(which(vecpvals<=alpha))/length(vecpvals) # loop to populate power vector. Power is the proportion lessthan ot equal to alpha
}
}
)