[R] Head or Tails game

David Winsemius dwinsemius at comcast.net
Sat Aug 4 03:49:57 CEST 2012


On Aug 3, 2012, at 5:55 PM, darnold wrote:

> Hi,
>
> Reading about a "Heads and Tails" game in
> http://www.dartmouth.edu/~chance/teaching_aids/books_articles/probability_book/amsbook.mac.pdf
> Introduction to Probability  (Example 1.4, pp. 5-8).
>
> You toss a coin 40 times. If heads, Peter wins $1, tails, he loses  
> $1. I
> think I can do that ok with:
>
> winnings <- sum(sample(c(-1,1), 40, replace=TRUE))
>
> But I have to do it 10,000 times and I have to record and collect the
> winnings. In other languages, I would probably use a for loop and  
> "push"
> each winnings into some sort of collective array or vector. However,  
> for
> loops seem to be discouraged in R and it seems the same can be said  
> for
> "pushing" a calculation onto a vector. So, can someone give me some  
> guidance
> on how to collect 10,000 winnings?

What's wrong with:

set.seed(123)  # always good to make reproducible
winnings <- sum(sample(c(-1,1), 10000, replace=TRUE))

>
> The second part of the game asks us to keep track of how often Peter  
> is in
> the lead during each game. Obviously, he is in the lead at any  
> moment his
> cumulative winnings are positive. But the game requires that we also  
> do
> something at the moment the cumulative winnings are zero.

?cumsum
?which

> (1) if the
> previous cumulative sum was nonnegative, then the zero counts a  
> "staying in
> the lead." So, for example, during a single game, Peter might be in  
> the lead
> for say 34 out of the 40 tosses. I must record the 34 and perform  
> the game
> 9,999 more times, each time recording the number of times that Peter  
> is in
> the lead.

? replicate

> So again, any thoughts on how to do  this without for loops and
> "pushing?"
>
> Thanks for the help. Great list.
>
> David Arnold
>

-- 

David Winsemius, MD
Alameda, CA, USA



More information about the R-help mailing list