Introduction

This document describes how to use the functions in the ld.sim package to simulate linkage disequilibrium in populations of haplotypes. Haplotypes have 2 or more diallelic loci. The loci are all on the same linkage group and the user specifies the recombination frequencies. The model can also simulate positive or negative selection on one or more loci.

To do these exercises, you will need to have R and RStudio installed on your computer. You can download the latest version of R from CRAN and you will find RStudio here.

This document assumes you have a basic familiarity with the layout of RStudio.

It is also assumed that you know the very basics of working with R Markdown documents. At a minimum you need to know how to work with code chunks and how to knit a markdown document into a html document.

  • For a nice gentle introduction you can check out this free tutorial on DataCamp

Setup

For this tutorial, you will work in an R Markdown document within an R Project. To create an R Project and R Markdown document, you will need to have previously installed R and RStudio.

Create an R Project

R Projects within RStudio are a convenient way to keep all the scripts and other files for a project organized together. The here package works within an R Project to help locate data and other files relative to the main project folder. This avoids having to specify a working directory (which can cause major headaches) and also makes it easy to use relative paths in your coding. Relative paths make it easy to share your code with others and to work on a project on different machines.

You should first decide where you want to store your project on your computer. I suggest you go with a meaningful folder name like ‘Linkage_Disequilibrium’. Create your project folder in a location you will remember using your operating system’s file manager.

To create an R Project, click the File menu and select the New Project… option. A popup will appear and ask you whether you want to create a new directory or use an existing directory. Select existing directory and in the next window browse to the folder you just created and click Create Project.

Create an R Markdown Document

To create a new RMarkdown document, click the File menu, hover over the New File option, and select R Markdown….

This will bring up a window where you can specify the title of your document. Title your document ‘Example Simulations’ or something similar.

New R Markdown documents include some demo code, which you will not need. Delete everything below the first code chunk.

Finally, save your document with the filename ‘example_simulations.Rmd’.

Package Installation

To run the simlations and do the exercises below, you will need to install some external packages. The packages you will need are:

  • ggplot2
  • here
  • ld.sim

The first two packages are available from CRAN and you can install them by pasting the following code into the R console:

install.packages("ggplot")
install.packages("here")

To install the latest version of the ld.sim package, run the following code in the R console:

install.packages("https://michaelfrancenelson.github.io/r_packages/ld.sim.tar.gz", repos = NULL)

Once the packages are installed, you don’t need to install them again unless you update your version of R or you want to get a newer version of the packages.

Loading ld.sim

To run a simulation you first need to load the ld.sim package using the following code:

require(ld.sim)

You should make a new chunk at the top of your R Markdown document and paste this code into it. Run the chunkk by clicking on the Run button in the upper right of the editor window and selecting Run Current Chunk. Once you have loaded the package, the simulation functions are available for use.

Example Simulations

For this section, you should copy and paste the code from the examples into code chunks that you create in your example simulations R Markdown document.

I provide complete code for the first several examples. You will need to use the example code as a template for the later examples for which I do not provide the code.

Example 1: 2 Loci, Small Population

To learn the syntax of the simulator, you will first create a simple population with two unlinked loci with no natural selection.

Create a first level header in your document by typing a pound sign (#) outside of a code chunk. Give you header a descriptive name like “Example” or “Tutorial”.

Now make a second level header (by using two pound signs) and call the section ‘Example 1: 2 Loci, Small Population’

Create a new code chunk.

To run a simulation, you first need to create a starting population of haplotypes using the init_pop() function. To view the documentation for this function, type the following code into the R Console:

?init_pop()

Take a moment to read the help entry, it contains lots of useful information!

The arguments to init_pop() specify the number of individual haplotypes in the population, the initial proportion of haplotypes that are in linkage disequilibrium, and the frequencies of the dominant alleles at each locus. The number of loci is inferred from the length of the dom_allele_freq argument.

Let’s create a population of 100 haplotypes with 5% of the initial haplotypes in complete disequilibrium and the dominant alleles at both loci for the remaining haplotypes at 50%.

Note the syntax for specifying the allele frequencies uses the c() function with two values separated by a comma.

pop1 = init_pop(n = 100, linked_initial_pct = 0.05, dom_allele_freq = c(0.5, 0.5))

Note that I saved the populatoin to a variable called pop1.

We can view a summary of population-level statistics with the get_hap_stats() function:

get_hap_stats(pop1)
##       A     B hap_code count hap_name  p_A  p_B p_obs  p_exp      ld
## 1 FALSE FALSE       00    30       AB 0.57 0.49  0.30 0.2793  0.0207
## 2  TRUE FALSE       10    19       aB 0.43 0.49  0.19 0.2107 -0.0207
## 3 FALSE  TRUE       01    27       Ab 0.57 0.51  0.27 0.2907 -0.0207
## 4  TRUE  TRUE       11    24       ab 0.43 0.51  0.24 0.2193  0.0207

Some things to notice in the table:

  • Haplotypes are represented as rows in the table.
  • The counts of each haplotype are in the count column. You can read the alleles at each locus from the hap_name column. In this simulation each locus has two alleles. Allele 1, or the dominant allele, is denoted with a capital letter.
  • The first two columns give the names of the loci. A FALSE value indicates that the haplotype has the dominant allele (allele 1) at that locus.
    • How many haplotypes with dominant alleles at loci A and B are present in the population?
  • Allele frequencies are given in the p_A and p_B columns.
  • You can also see the observed (p_obs) and expected (p_exp) haplotype frequencies.
  • The column ld is the linkage disequilibrium for each haplotype. Linkage disequilibrium measures the difference between the observed haplotype frequency and the haplotype frequency you would expect to observe given the allele frequencies.

Now it’s time to run a simulation!

We’ll run a simulation with unlinked loci and no selection for 200 steps:

sim1 = simulate_ld(pop1, n_steps = 200)

The simulation may take a few seconds to run.

Note that I saved the output of the simulation to a variable called sim1.

We can view graphical summaries of the allele frequencies, haplotype frequencies, and linkage disequilibrium during the simulation.

First, let’s view the allele frequencies with the function gg_allele_freq():

gg_allele_freq(sim1)

In the plot, the different colored lines represent the frequency of the dominant allele for each locus throughout the simulation.

Try running the code for the simulation again and making another plot:

sim1 = simulate_ld(pop1, n_steps = 200)
gg_allele_freq(sim1)

You should see a different pattern when you run the simulation on your own computer. The simulation is stochastic meaning that it uses pseudorandom numbers. Each time you run the simulation you will get slightly different results.

Now let’s examine the haplotype frequencies:

gg_hap_freq(sim1)

How is this plot related to the allele frequency plot? Look back at the allele frequency plot and observe a time step range when the allele A was at an unusually high, or low frequency. Now examine the haplotype frequencies for haplotypes Ab and AB. Can you see a relationship between the two plots?

Next, we can examine the amount of linkage disequilibrium throughout the simulation:

gg_d_prime(sim1)

That plot looks a little crazy! Why do you think that is?

We simulated a small population: only 100 haplotypes representing just 50 diploid individuals. Small populations are subject to wild fluctuations in things like allele frequencies and linkage disequilibrium. In small populations, having just a couple more or less of a specific haplotype can drastically change the value of D`! The linkage disequilibrium plots will be more sensible when you simulate larger populations.

Example 2: 2 Loci, Large Population

Now it’s your turn to practice coding!

Create a second level header and call the section ‘Example 2: 2 Loci, Large Population’

Using the code above as a guide, create a population of 1000 haplotypes with two loci. This time, use the dom_allele_freq argument to specify that you’d like the initial frequency of the dominant alleles to be 40% at locus A and 60% at locus B. Also specify that you don’t want any haplotypes to initially be in disequilibrium.

  • Hint: use dom_allele_freq = c(0.4, 0.6) within your call to init_pop().
  • Hint: save your population to a variable called pop2.

Use get_hap_stats() to print a summary of your population. Here’s the output from my population:

##       A     B hap_code count hap_name   p_A   p_B p_obs    p_exp        ld
## 1 FALSE FALSE       00   225       AB 0.389 0.599 0.225 0.233011 -0.008011
## 2  TRUE FALSE       10   374       aB 0.611 0.599 0.374 0.365989  0.008011
## 3 FALSE  TRUE       01   164       Ab 0.389 0.401 0.164 0.155989  0.008011
## 4  TRUE  TRUE       11   237       ab 0.611 0.401 0.237 0.245011 -0.008011

Now let’s run a simulation with no linkage or selection. Create a variable sim2 to hold the results of a simulation running for 200 steps.

Now create the three plots:

What differences do you notice between the plots of the first example simulation and the plots of the second one you just created? What was different between the populations?

Ask yourself, is genetic drift stronger in large, or small populations?

Example 3: 3 Loci

Make a new second level header for example 3.

Now let’s try simulating three loci. To create a population of haplotypes with three loci, you just need to specify three dominant allele frequencies in the dom_allele_freq argument:

pop3 = init_pop(n = 1000, linked_initial_pct = 0, dom_allele_freq = c(0.3, 0.5, 0.7))

I specified that I wanted initial dominant allele frequencies of 30%, 50%, and 70% for the three loci.

Examine the population stats:

##       A     B     C hap_code count hap_name   p_A   p_B   p_C p_obs      p_exp
## 1 FALSE FALSE FALSE      000   122      ABC 0.282 0.534 0.714 0.122 0.10751983
## 2  TRUE FALSE FALSE      100   252      aBC 0.718 0.534 0.714 0.252 0.27375617
## 3 FALSE  TRUE FALSE      010    76      AbC 0.282 0.466 0.714 0.076 0.09382817
## 4  TRUE  TRUE FALSE      110   264      abC 0.718 0.466 0.714 0.264 0.23889583
## 5 FALSE FALSE  TRUE      001    48      ABc 0.282 0.534 0.286 0.048 0.04306817
## 6  TRUE FALSE  TRUE      101   112      aBc 0.718 0.534 0.286 0.112 0.10965583
## 7 FALSE  TRUE  TRUE      011    36      Abc 0.282 0.466 0.286 0.036 0.03758383
## 8  TRUE  TRUE  TRUE      111    90      abc 0.718 0.466 0.286 0.090 0.09569217
##             ld
## 1  0.014480168
## 2 -0.021756168
## 3 -0.017828168
## 4  0.025104168
## 5  0.004931832
## 6  0.002344168
## 7 -0.001583832
## 8 -0.005692168

Notice that with three loci, there are 8 possible haplotypes.

I’m going to run a simulation without selection or linkage for 200 time steps and plot the results.

  • This simulation will take a little bit longer to run. More loci = greater model complexity and longer run time.
sim3 = simulate_ld(pop3, n_steps = 200)
gg_allele_freq(sim3)

Notice that all the haplotypes remain at low frequency throughout the simulation. To make it easier to see, we can specify the y-axis limits to the plot with the ylim argument.

gg_hap_freq(sim3, ylim = c(0, 0.3))

gg_d_prime() also accepts a ylim argument:

gg_d_prime(sim3, ylim = c(-0.3, 0.3))

Notice that there are now three lines in the D’ plot: one for each pair of Loci. This simulation calculates pairwise linkage disequilibrium between two Loci. It is possible to calculate a multilocus linkage disequilibrium coefficient, but the calculation is complex and the pairwise values are often more useful.

Example 4: 3 Loci with Selection

Make another second-level header for this section

Now let’s see what happens when we add selection to two of the loci.

Let’s create another population of 1000 haplotypes with 3 loci, but this time let’s set the initial dominant allele frequency for locus A and C to 50% and the initial frequency for locus B to 5%. Keep the initial linked percent at 0.

I’ll let you figure out the code using the example above as a template!

Here are the population stats:

##       A     B     C hap_code count hap_name   p_A  p_B   p_C p_obs      p_exp
## 1 FALSE FALSE FALSE      000    11      ABC 0.475 0.05 0.477 0.011 0.01132875
## 2  TRUE FALSE FALSE      100    10      aBC 0.525 0.05 0.477 0.010 0.01252125
## 3 FALSE  TRUE FALSE      010   211      AbC 0.475 0.95 0.477 0.211 0.21524625
## 4  TRUE  TRUE FALSE      110   245      abC 0.525 0.95 0.477 0.245 0.23790375
## 5 FALSE FALSE  TRUE      001    14      ABc 0.475 0.05 0.523 0.014 0.01242125
## 6  TRUE FALSE  TRUE      101    15      aBc 0.525 0.05 0.523 0.015 0.01372875
## 7 FALSE  TRUE  TRUE      011   239      Abc 0.475 0.95 0.523 0.239 0.23600375
## 8  TRUE  TRUE  TRUE      111   255      abc 0.525 0.95 0.523 0.255 0.26084625
##            ld
## 1 -0.00032875
## 2 -0.00252125
## 3 -0.00424625
## 4  0.00709625
## 5  0.00157875
## 6  0.00127125
## 7  0.00299625
## 8 -0.00584625

So far this is similar to what we have done before.

To include selection in your simulation, you must provide a vector of selection coefficients using the argument sel_coefs. The length of this vector is the same as the number of loci in the population.

I’m going to set a positive selection coefficient of 0.05 on locus B and a negative selection coefficient of -0.1 on locus C. I’ll run the simulation for 200 time steps again:

sim4 = simulate_ld(pop4, n_steps = 200, sel_coefs = c(0, 0.05, -0.1))

Take a look at the allele frequencies:

What happened to the frequencies of the dominant alleles at loci B and C? Is that what you expected?

We can look at the haplotype frequency and D’:

Notice that there are a lot more haplotypes this time!

Take a look at some of the haplotypes that increased in frequency. Did they tend to have the B allele?

What about haplotypes that had the C allele?

And now D’:

In my simulation there were some crazy things happening just after time step 50 and around time step 150. Take a look at the allele and haplotype frequency plots and see if you can figure out what is going on.

Example 5: 3 Loci with Linkage and Selection

The last element to add to the simulation is linkage!

To reduce the effects of random drift, we will use populations of 10,000 haplotypes for this example.

To specify linkage, you must pass the argument rec_map to the simulate_ld() function. The rec_map argument represents the recombination frequencies between successive loci on the chromosome. For example, with 3 loci (A, B, and C) the following code would run a simulation with a recombination frequency of 0.5% between loci A and B, and a recombination frequency of 5% between loci B and C.

This time, I’m also going to run a scenario in which the dominant allele A is a new mutation and is initially only present in the haplotype ABC. Allele B is initially rare and allele C is common.

pop5 = init_pop(n = 10000, linked_initial_pct = 0.1, dom_allele_freq = c(0, 0.05, 0.7))
sim5a = simulate_ld(pop5, n_steps = 200, rec_map = c(0.005, 0.05))

My allele frequencies would look something like this:

And the linkage disequilibrium plot looks like this:

Now that is a more interesting pattern! Did the A-B pair remain in linkage disequilibrium longer? If so, why? What about the other two pairs of loci?

If I wanted to apply the same selection coefficients from example 4, I could use:

sim5b = simulate_ld(pop5, n_steps = 200, rec_map = c(0.005, 0.05), sel_coefs = c(0, 0.05, -0.1))

Now that’s different! Can you explain why the frequency of allele A increased?

And now for D’:

gg_d_prime(sim5b)

See if you can relate the weird patterns in D’ to the allele frequencies.