[R] Need some help

Marc Schwartz marc_schwartz at comcast.net
Tue Oct 16 21:13:24 CEST 2007

On Tue, 2007-10-16 at 11:53 -0700, azzza wrote:
> ok, so suppose a coin is tossed 1000 times. Each time head occurs, we win a
> dollar, otherwise we lose a dollar. Let S(n) be our accumulated winnings
> after n tosses. For instance, if the sequence HHHTT occurs in the first five
> tosses, then S(5) = $1.00 wheras if the sequence HTTTT occurs, S(5) =-$3. So
> now, we want to see how many times during the 1000tosses S9n) will go from a
> positive balance to a negative balanc eor the other way around. So for our
> simulation, S(n) is computed by adding one to S(n-1) if a head occurs, and
> subtracting one form S(n-1) if a tail occurs. A change in sign will occur on
> the nth toss in one of two ways: S(n-2)=1, S(n-1)=0 and, S(n)= -1 OR S(n-2)
> = -1, S(n-1)=0 and S(n)=1. This is equivalent to S(n-2)+ S(n-1)+ S(n)=0. 
> so now, n is the numbe rof tosses,  S(n) is the number of heads minus the
> number of tails in n tosses and C is the number of times S(n) changes sign. 
> so we initialize n=0, S(-1)=0, S(0)=0, and C(0)=0 
> now we should, 
> -generate u, a uniform number, with the increment, n=n+1 ....(our n=1000) 
> -if u<1/2, that is tails occur, set S(n)=S(n-1)-1, and also set
> S(n)=S(n-1)+1 
> - If S(n) +S(n-1)+S(n-2)=0, then increment C=C+1. 
> My issue is simulating this in R, where I need to code the number of sign
> changes, the frequency of heads, and to plot S(n) versus n in a line graph.
> for each coin toss, the number of sign changes could either be a positive
> number, zero, or a negative number. 

I believe that Jim had the right approach in his reply here:


and Prof. Koenker has given you a reference on the theory:




More information about the R-help mailing list