循环执行R中的一系列步骤

时间:2014-01-01 11:40:51

标签: r

我试图写一个涉及循环并被卡住的短程序。 我的代码:

Screen=(rpois (1, lambda=3)) 
y=runif(Screen,0,1) 
Base=length(which(y<0.5 | y==0.5 )) 
SF=length(which(y>0.5)) 
Visits=cbind(Screen,Base,SF)  

我想使用泊松生成模拟,然后为下一个级别选择值(在我的情况下为Base)。我的选择标准是0.5%。如果Screen返回值4,我将生成4个随机数。介于0和1之间。其中,我会计算nos。具有小于或等于0.5的值并将其置于基线中。其余的将去SF。我需要把它放在一个循环中,这样我得到一个包含Screen,Base和SF列的表,当Baseline中的累积值达到100时,这将停止。所以我希望Screen继续生成值,直到Base达到100列Base的值的值应该恰好为100。

1 个答案:

答案 0 :(得分:0)

您可以将代码置于while循环中:

baseSum=0.0
Visits = NULL
while(baseSum < 100)
{
  Screen=(rpois (1, lambda=3)) 
  y=runif(Screen,0,1) 
  Base = length(which(y<=0.5))
  baseSum = baseSum + Base
  SF = Screen - Base
  Visits=rbind(Visits,c("Screen"=Screen,"BaseCount"=Base,"SFCount"=SF))    
}
plot(cumsum(Visits[,"BaseCount"]),type="b");grid()
sum(Visits[,"BaseCount"])

或者你可以制作大量的泊松样本,然后切断你需要的东西:

tooManyRuns = t(sapply(rpois (110, lambda=3) , function(X) { y=runif(X,0,1); Base = length(which(y<=0.5)); SF = X-Base; return(c("Screen"=X,"BaseCount"=Base,"SFCount"=SF)) } ))
Visits =tooManyRuns[1:min(which(cumsum(tooManyRuns[,"BaseCount"])>=100.0)),]
plot(cumsum(Visits[,"BaseCount"]),type="b");grid()
sum(Visits[,"BaseCount"])

我假设您正在进行一些实验,以了解在此转换中您需要多少次运行。如果是这种情况,那么你可以像这样包装它:

numRunsNeeded = sapply(1:1000,
       function(...)
       {
        tooManyRuns = t(sapply(rpois (110, lambda=3) , function(X) { y=runif(X,0,1); Base = length(which(y<=0.5)); SF = X-Base; return(c("Screen"=X,"BaseCount"=Base,"SFCount"=SF)) } ))
        return(min(which(cumsum(tooManyRuns[,"BaseCount"])>=100.0)))
       } )   

plot(density(numRunsNeeded));rug(numRunsNeeded);abline(v=mean(numRunsNeeded));abline(v=median(numRunsNeeded),lty=2)

请注意,您没有获得66.666但是67.xx,因为您的基本数量平均为&gt; 100(最后一次运行不一定会产生你需要精确达到100的整数)。