## Chapter 9. Loops

Loops are R’s method for repeating a task, which makes them a useful tool for programming simulations. This chapter will teach you how to use R’s loop tools.

Let’s use the `score`

function to solve a real-world problem.

Your slot machine is modeled after real machines that were accused of fraud. The machines appeared to pay out 40 cents on the dollar, but the manufacturer claimed that they paid out 92 cents on the dollar. You can calculate the exact payout rate of your machine with the `score`

program. The payout rate will be the expected value of the slot machine’s prize.

## Expected Values

The expected value of a random event is a type of weighted average; it is the sum of each possible outcome of the event, weighted by the probability that each outcome occurs:

You can think of the expected value as the average prize that you would observe if you played the slot machine an infinite number of times. Let’s use the formula to calculate some simple expected values. Then we will apply the formula to your slot machine.

Do you remember the `die`

you created in Part I?

die`<-`

c`(`

`1`

`,`

`2`

`,`

`3`

`,`

`4`

`,`

`5`

`,`

`6`

`)`

Each time you roll the die, it returns a value selected at random (one through six). You can find the expected value of rolling the die with the formula:

The s are the possible outcomes of rolling ...

Get *Hands-On Programming with R* now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.