The dragon breeding simulation is written in R (a programming language). The most important aspect of the simulation is that dragons are created randomly.
What it means is that the program creates each dragon by taking one chromosome of each pair of chromosomes from each parent on random. We do not specify which chromosome of each pair will be taken, and the chances of each chromosome being passed to the offspring are the same.
If you run the simulation many times, you might obtain different results (because of randomness).
Think about tossing a coin – we can have two choices: we either get Heads or Tails.
1. Simulating a toss of a coin in R
First, we declare that we have an object, a coin, that contains two sides (Heads and Tails). In R, it will be written like this:
coin = c(“Heads”, “Tails”)
Another way would be to write: coin <- c(“Heads”, “Tails”). The “=” and “<-” assignment signs can be used interchangeably.
Secondly, we toss a coin. In R, we could write it like this:
From all the elements of coin (“Heads” or “Tails”), pick one sample.
Every time we simulate tossing a coin, we can get a different result. Try it yourself by running the code below.
Instructions: hit the Run/Play button to simulate one toss of the coin. The result will appear in the right panel. You can do it as many times as you want!
2. Simulating a coin toss multiple times
We can change the number of times we toss a coin. Let’s do it 10 times.
Because we want to repeat the same thing (coin toss) 10 times, we can put the coin toss inside a for loop. The for loop will repeat what we put inside it a number of times that we specify. In this case, we declared that we want to loop 10 times: from 1 to 10 (1:10).
To see the result of each coin toss, we have to put the coin toss action inside a print command. Otherwise, we will not see it. If you want, you can change how many times the for loop will run (for example, you can put 1:100). You can also remove the print() wrapper (and write simply: sample(coin, 1) instead), to see what happens.
We can change the code a little, so that now we can count how many times heads or tails were tossed.
We are adding two additional objects: heads and tails counters. Before we start tossing a coin, we set our counters to 0. Then, we use the If else function to count the number of heads or tails in the for loop. Once the for loop finishes, we print out the results.
We would expect to get the same number of heads and tails. However, for small trials, the differences can be quite high (for example, for a trial of size 10, instead of expected 5 heads and 5 tails, we can often get 7 heads and 3 tails, or vice versa). If you increase the number of trials, you will get closer to the expected values.
You can adjust the code above, to increase the number of for loop runs, and to see the effect it will have on the observed outcome.