user3356728
user3356728

Reputation: 47

Using a for loop nested in a while loop in r

Experiment:'X is a binomial of five trials and p = 0.5, where X is the number of heads. Ysample is a binomial of X trials and p=0.5, where Ysample is the number of heads.' T is the number of times the experiment is repeated until the value of Ysample>=3. This is the code:

while (Ysample[i]<3){
length(X)=n
    length(Y)=n
    X=c(1:n)
    Y=c(1:n)
    i=1
    X[i]=sum(rbinom(5,1,0.5))
    Ysample[i]=sum(rbinom(X[i],1,0.5))
    i=i+1
    }
    T=n

I am unsure why it is not working and why no matter how many times I run it I always get T=10000?

Upvotes: 0

Views: 245

Answers (2)

vaettchen
vaettchen

Reputation: 7659

Does this what you want?

T <- 0
Ysample <- 0

while( Ysample < 3 )
{
    X <- sum( rbinom( 5, 1, 0.5 ) )
    Ysample <- sum( rbinom( X, 1, 0.5 ) )
    T <- T + 1
}

cat( "T =  ", T, "\n\n" )

Upvotes: 1

R. Barzell
R. Barzell

Reputation: 674

Check what you are setting n to. T is simply set to n at the end of the loop. It isn't computed or anything.

Also, you may want to consider using higher order functions; while R can handle loops, it does much better without them, and it's more idiomatic R to use higher order functions and the default "vectorizing" behavior of operations.

Upvotes: 1

Related Questions