5 Loops

5.1 For-loop

The for-loop is one of the most powerful tools in programming. When you are conduction asset pricing univariate/ bivariate portfolio sorts are one way to identify risk premiums. Imagine you have data on daily stock returns for two stocks and you want to buy at time t the best performing stock in t-1. Such a task can easily be handled with a for-loop. I will start with a simple for loop and show you in a later chapter how you can do portfolio sorts.

The following example teaches the notation in a for-loop and shows you what it does. First, you specify the index (i - this couls also be another variable). Second, you specify the range of the index (here: 1:5). This means, that i will take all integer values from 1 to 5. After the curly brackets follows the task. Here we simply specify that we want to print the index.

## [1] 1
## [1] 2
## [1] 3
## [1] 4
## [1] 5

Here is another simple example how to use for loops. Notice that the index variable can be chosen freely (here: x). This is important when you do nested for-loops.

## [1] 4
## [1] 5
## [1] 6
## [1] 7

A nested for loop, is a loop within a loop.

## [1] 1
## [1] 1
## [1] 1
## [1] 2
## [1] 2
## [1] 1
## [1] 2
## [1] 2

5.2 Solve the Monty Hall Problem

Monty Hall was the host of a famous game show called Let’s make a deal in the 70s. During the game show, the competitors were confronted with three closed doors. Behind one of the three doors is the main prize (e.g. a car) and behind the other two doors are goats. Initially, the competitor of the game show chooses a door, where he thinks the main prize is located (e.g. door 1). After, Monty Hall would open one of the other two doors (e.g. door 3 - which does not contain the main prize) and asks the competitor: “Do you want to switch to door No. 2?”

**The Monty Hall problem**

Figure 5.1: The Monty Hall problem

So what should the competitor do? The following simulation illustrates that by switching doors the competitor can increase his winning probability from initially 33.3% to 66.6%.

The following code simulates two different competitors. The first competitor chooses randomly one of the three doors and won’t change his decision (strategy 1). The second competitor picks randomly as well but switches the door in the second phase of the game (strategy 2).

The competitors randomly choose a door (e.g. 1,2 or 3).

Set a variable that contains the main prize.

## [1] 0.37347
## [1] 0.62653