Introduction

In this worked example you will replicate a PCA on a published dataset.

The example is split into 2 Parts:

In this Data Preparation phase, you will do the following things:

  1. Load the SNP genotypes in .vcf format (vcfR::read.vcfR())
  2. Extract the genotypes into an R-compatible format (vcfR::extract.gt())
  3. Rotate the data into the standard R analysis format (t())
  4. Remove individuals (rows) from the data set that have >50% NAs (using a function I wrote)
  5. Remove SNPs (columns) that are fixed
  6. Impute remaining NAs (using a for() loop)
  7. Save the prepared data as a .csv file for the next step (write.csv())

Biological background

This worked example is based on a paper in the journal Molecular Ecology from 2017 by Jennifer Walsh titled Subspecies delineation amid phenotypic, geographic and genetic discordance in a songbird.

The study investigated variation between two bird species in the genus Ammodramus: A. nenlsoni and A. caudacutus.

The species A. nenlsoni has been divided into 3 sub-species: A. n. nenlsoni, A.n. alterus, and A n. subvirgatus. The other species, A. caudacutus, has been divided into two subspecies, A.c. caudacutus and A.c. diversus.

The purpose of this study was to investigate to what extent these five subspecies recognized by taxonomists are supported by genetic data. The author’s collected DNA from 75 birds (15 per subspecies) and genotyped 1929 SNPs. They then analyzed the data with Principal Components Analysis (PCA), among other genetic analyzes.

This tutorial will work through all of the steps necessary to re-analyze Walsh et al.s data

Tasks

In the code below all code is provided. Your tasks will be to do 2 things:

  1. Give a meaningful title to all sections marked “TODO: TITLE”
  2. Write 1 to 2 sentences describing what is being done and why in all sections marked “TODO: EXPLAIN”

Preliminaries

Load the vcfR and other packages with library().

library(vcfR)    
## Warning: package 'vcfR' was built under R version 4.2.2
## 
##    *****       ***   vcfR   ***       *****
##    This is vcfR 1.13.0 
##      browseVignettes('vcfR') # Documentation
##      citation('vcfR') # Citation
##    *****       *****      *****       *****
library(vegan)
## Loading required package: permute
## Loading required package: lattice
## This is vegan 2.6-2
library(ggplot2)
library(ggpubr)

Make sure that your working directory is set to the location of the file all_loci.vcf.

getwd()
## [1] "C:/Users/Owner/Downloads"
list.files()
##   [1] "09-PCA_worked_example-SNPs-part1.Rmd"                                                                                   
##   [2] "1 David Bartholomae_ Anthony Petrosky_ Stacey Waite - Ways of Reading_ An Anthology for Writers-Bedford_St Martinâs.pdf"
##   [3] "1.159051856-159301856.ALL.chr1_GRCh38.genotypes.20170504.vcf.gz"                                                        
##   [4] "10-PCA_worked_example-SNPs-part2.Rmd"                                                                                   
##   [5] "135-CKO1511.ab1"                                                                                                        
##   [6] "135-CKO1511.seq"                                                                                                        
##   [7] "135-DRD114.ab1"                                                                                                         
##   [8] "135-DRD114.seq"                                                                                                         
##   [9] "135-oCG535.ab1"                                                                                                         
##  [10] "135-oCG535.seq"                                                                                                         
##  [11] "1622723_10204891200860456_5218212751136820825_n (1).jpg"                                                                
##  [12] "1622723_10204891200860456_5218212751136820825_n.jpg"                                                                    
##  [13] "17.29734902-2997490.vcf"                                                                                                
##  [14] "17.29734902-29974902.ALL.chr17_GRCh38.genotypes.20170504.vcf.gz"                                                        
##  [15] "18301868_2075085546071164_8004292719397841424_n.jpg"                                                                    
##  [16] "18882294_10207965920420867_1945507242014203763_n.jpg"                                                                   
##  [17] "18921972_10207973932861173_4629340555711013467_n.jpg"                                                                   
##  [18] "18922042_10207966156346765_1507188139737044483_n.jpg"                                                                   
##  [19] "19029431_10207973932821172_3463105186989021425_n.jpg"                                                                   
##  [20] "19554597_10158953325465494_2717563150007352944_n.jpg"                                                                   
##  [21] "2.5.4. Baza za e komunikaciju  (1).xlsx"                                                                                
##  [22] "2.5.4. Baza za e komunikaciju .xlsx"                                                                                    
##  [23] "26166401_1557988294294656_1226955529190907164_n.jpg"                                                                    
##  [24] "28379824_1614519581974860_7128273527018490516_n.png"                                                                    
##  [25] "29178318_10214955102731589_2041979863727865856_n.jpg"                                                                   
##  [26] "29216412_10215512908436507_997140712216989911_n.jpg"                                                                    
##  [27] "29496013_10215512908396506_8176294350108610328_n.jpg"                                                                   
##  [28] "29542474_10106299798555208_2208760086941185910_n.jpg"                                                                   
##  [29] "29572370_10106299798699918_8742511690257864169_n.jpg"                                                                   
##  [30] "30226677_1364892006950893_6440214249586294784_n.jpg"                                                                    
##  [31] "35799443_10210290732579718_4549003848370356224_n.jpg"                                                                   
##  [32] "38222529_1937781376260651_7424435383040999424_n.jpg"                                                                    
##  [33] "3rd Annual Bark in the Park Shelter & Rescue Application 2018.pdf"                                                      
##  [34] "40100508_329269320979269_7469879856474357760_n.jpg"                                                                     
##  [35] "40178222_329269360979265_1822871123574915072_n.jpg"                                                                     
##  [36] "43030782_10210882262607599_9140948449053638656_n.jpg"                                                                   
##  [37] "69997921_10157459730176558_8960783513108348928_o.jpg"                                                                   
##  [38] "all_loci.vcf"                                                                                                           
##  [39] "allomtery_3_scatterplot3d (1).Rmd"                                                                                      
##  [40] "ApE_win_current.zip"                                                                                                    
##  [41] "bio lab 2 presentation slides.pdf"                                                                                      
##  [42] "c48e924cfd9ab136d7fca4dfa33a17a2.jpg"                                                                                   
##  [43] "center_function.R"                                                                                                      
##  [44] "ChromeSetup (1).exe"                                                                                                    
##  [45] "ChromeSetup.exe"                                                                                                        
##  [46] "Closing Questions.pdf"                                                                                                  
##  [47] "cmpinf401-Lecture1.pptx"                                                                                                
##  [48] "cmpinf401-Lecture10.pptx"                                                                                               
##  [49] "cmpinf401-Lecture11.pptx"                                                                                               
##  [50] "cmpinf401-Lecture12.pptx"                                                                                               
##  [51] "cmpinf401-Lecture13.pptx"                                                                                               
##  [52] "cmpinf401-Lecture15.pptx"                                                                                               
##  [53] "cmpinf401-Lecture16.pptx"                                                                                               
##  [54] "cmpinf401-Lecture17.pptx"                                                                                               
##  [55] "cmpinf401-Lecture18.pptx"                                                                                               
##  [56] "cmpinf401-Lecture19.pptx"                                                                                               
##  [57] "cmpinf401-Lecture2.pptx"                                                                                                
##  [58] "cmpinf401-Lecture20.pptx"                                                                                               
##  [59] "cmpinf401-Lecture21.pptx"                                                                                               
##  [60] "cmpinf401-Lecture22.pptx"                                                                                               
##  [61] "cmpinf401-Lecture3.pptx"                                                                                                
##  [62] "cmpinf401-Lecture4.pptx"                                                                                                
##  [63] "cmpinf401-Lecture5.pptx"                                                                                                
##  [64] "cmpinf401-Lecture6.pptx"                                                                                                
##  [65] "cmpinf401-Lecture7.pptx"                                                                                                
##  [66] "cmpinf401-Lecture8.pptx"                                                                                                
##  [67] "cmpinf401-Lecture9.pptx"                                                                                                
##  [68] "CODE_CHECKPOINT-first_rstudio_script.R"                                                                                 
##  [69] "code_checkpoint_vcfR.html"                                                                                              
##  [70] "code_checkpoint_vcfR.Rmd"                                                                                               
##  [71] "desktop.ini"                                                                                                            
##  [72] "Dictionary.java"                                                                                                        
##  [73] "dinog.csv"                                                                                                              
##  [74] "DropboxInstaller.exe"                                                                                                   
##  [75] "Duplication secrets.mp4"                                                                                                
##  [76] "EarnBackInvestment_infographic-CA.02(CAD).pdf"                                                                          
##  [77] "feature_engineering_intro_2_functions-part2 (1).Rmd"                                                                    
##  [78] "feature_engineering_intro_2_functions-part2.Rmd"                                                                        
##  [79] "Final Report - Sandra Milanovic.Rmd"                                                                                    
##  [80] "Firefox Installer.exe"                                                                                                  
##  [81] "flashplayer32au_ga_install.exe"                                                                                         
##  [82] "fst_exploration_in_class-STUDENT.Rmd"                                                                                   
##  [83] "Group B UG_j cand 15.xlsx"                                                                                              
##  [84] "Ignite_Meal_Planner.pdf"                                                                                                
##  [85] "INCLAS_1.APE"                                                                                                           
##  [86] "invite.ics"                                                                                                             
##  [87] "jdk-18_windows-x64_bin.exe"                                                                                             
##  [88] "LaunchPackFlyer.pdf"                                                                                                    
##  [89] "loading and transposing VCF files.Rmd"                                                                                  
##  [90] "mail.jpg"                                                                                                               
##  [91] "MeasuringChart.pdf"                                                                                                     
##  [92] "Minka_Lepic__AMF_Book.pdf"                                                                                              
##  [93] "Minka_Lepic__MS_Book (1).pdf"                                                                                           
##  [94] "Minka_Lepic__MS_Book.pdf"                                                                                               
##  [95] "MuEditor-win64-1.1.1.msi"                                                                                               
##  [96] "NewRPB1.ape"                                                                                                            
##  [97] "npp.8.4.5.Installer.x64.exe"                                                                                            
##  [98] "PCA-missing_data.Rmd"                                                                                                   
##  [99] "PCA-on-SNPs-data-from-a-vcf-file-Part-1---Data-Preparation.html"                                                        
## [100] "PCA on SNPs data from a vcf file Part 1 - Data Preparation.Rmd"                                                         
## [101] "Personal VCF Data.R"                                                                                                    
## [102] "photo.html"                                                                                                             
## [103] "Pitt_Printing_Client_Win64_1930.exe"                                                                                    
## [104] "PLR3.docx"                                                                                                              
## [105] "portfolio_ggpubr_log_transformation.Rmd"                                                                                
## [106] "PowerShell-7.2.6-win-x64.msi"                                                                                           
## [107] "R-4.2.1-win.exe"                                                                                                        
## [108] "RPB1.ape"                                                                                                               
## [109] "rsconnect"                                                                                                              
## [110] "RStudio-2022.07.2-576.exe"                                                                                              
## [111] "S288C_YIL143C_SSL2_coding.fsa"                                                                                          
## [112] "Sandra Milanovic - Resume.pdf"                                                                                          
## [113] "Sequence 3 Full Length.ape"                                                                                             
## [114] "Sequence 3.ape"                                                                                                         
## [115] "Sequence 6 Full Length.ape"                                                                                             
## [116] "Sequence 6.ape"                                                                                                         
## [117] "Sequence 9 Full Length.ape"                                                                                             
## [118] "Sequence 9.ape"                                                                                                         
## [119] "Setting-a-working-directory-and-loading-data.html"                                                                      
## [120] "Setting a working directory and loading data.Rmd"                                                                       
## [121] "SNPs_cleaned.csv"                                                                                                       
## [122] "SolsticeClientWin_V2A0AE303D6PCF6CIEBF03067.exe"                                                                        
## [123] "Spring-2023.png"                                                                                                        
## [124] "SSL2.ape"                                                                                                               
## [125] "streamladder-Bad Nurse Bad Nurse.mp4"                                                                                   
## [126] "SystemInterfaceFoundation (1).exe"                                                                                      
## [127] "SystemInterfaceFoundation.exe"                                                                                          
## [128] "sz145010w64en.exe"                                                                                                      
## [129] "Team Hangout 151019 Canva & Adding cool graphics to photos.mp4"                                                         
## [130] "transpose_VCF_data.Rmd"                                                                                                 
## [131] "Untitled"                                                                                                               
## [132] "USProductBenefits10021701.02.pdf"                                                                                       
## [133] "vcfR_test.vcf"                                                                                                          
## [134] "vcfR_test.vcf.gz"                                                                                                       
## [135] "vegan_PCA_amino_acids-STUDENT.Rmd"                                                                                      
## [136] "vegan_pca_with_msleep-STUDENT.Rmd"                                                                                      
## [137] "VID-20180706-WA0008 (1).MP4"                                                                                            
## [138] "VID-20180706-WA0008 (2).MP4"                                                                                            
## [139] "VID-20180706-WA0008 (3).MP4"                                                                                            
## [140] "VID-20180706-WA0008 (4).MP4"                                                                                            
## [141] "VID-20180706-WA0008 (5).MP4"                                                                                            
## [142] "VID-20180706-WA0008 (6).MP4"                                                                                            
## [143] "VID-20180706-WA0008 (7).MP4"                                                                                            
## [144] "VID-20180706-WA0008 (8).MP4"                                                                                            
## [145] "VID-20180706-WA0008 (9).MP4"                                                                                            
## [146] "VID-20180706-WA0008.MP4"                                                                                                
## [147] "walsh2017morphology.csv"                                                                                                
## [148] "wsabbs2.exe"                                                                                                            
## [149] "wsainstall (1).exe"                                                                                                     
## [150] "wsainstall.exe"                                                                                                         
## [151] "xyng.html"                                                                                                              
## [152] "xyng_files"                                                                                                             
## [153] "xyngular 01.png"                                                                                                        
## [154] "xyngular_ignite-system_blog-res.2e16d0ba.fill-1102x675 (1).jpg"                                                         
## [155] "xyngular_ignite-system_blog-res.2e16d0ba.fill-1102x675.jpg"                                                             
## [156] "Zoom_1a31594aa0d74997 (1).exe"                                                                                          
## [157] "Zoom_1a31594aa0d74997 (2).exe"                                                                                          
## [158] "Zoom_1a31594aa0d74997.exe"                                                                                              
## [159] "Zoom_b71392b14010d162.exe"                                                                                              
## [160] "Zoom_c2528d90a4c2f52a.exe"                                                                                              
## [161] "Zoom_o42l8sofizku_6a7678722eea9051 (1).exe"
list.files(pattern = "vcf")
##  [1] "1.159051856-159301856.ALL.chr1_GRCh38.genotypes.20170504.vcf.gz"
##  [2] "17.29734902-2997490.vcf"                                        
##  [3] "17.29734902-29974902.ALL.chr17_GRCh38.genotypes.20170504.vcf.gz"
##  [4] "all_loci.vcf"                                                   
##  [5] "code_checkpoint_vcfR.html"                                      
##  [6] "code_checkpoint_vcfR.Rmd"                                       
##  [7] "PCA-on-SNPs-data-from-a-vcf-file-Part-1---Data-Preparation.html"
##  [8] "PCA on SNPs data from a vcf file Part 1 - Data Preparation.Rmd" 
##  [9] "vcfR_test.vcf"                                                  
## [10] "vcfR_test.vcf.gz"

Data preparation

TODO: Attribute Determination

##TODO: Reads the final attributes to the snaps in the vcf file

snps <- vcfR::read.vcfR("all_loci.vcf", convertNA  = TRUE)
## Scanning file to determine attributes.
## File attributes:
##   meta lines: 8
##   header_line: 9
##   variant count: 1929
##   column count: 81
## 
Meta line 8 read in.
## All meta lines processed.
## gt matrix initialized.
## Character matrix gt created.
##   Character matrix gt rows: 1929
##   Character matrix gt cols: 81
##   skip: 0
##   nrows: 1929
##   row_num: 0
## 
Processed variant 1000
Processed variant: 1929
## All variants processed

TODO: Extracting Data

##TODO: Extracts the data of SNPS and assigns it

snps_num <- vcfR::extract.gt(snps, 
           element = "GT",
           IDtoRowNames  = F,
           as.numeric = T,
           convertNA = T,
           return.alleles = F)

TODO: Transpose the Data

##TODO: We are transposing the number of snaps and assigning it to its own variable

snps_num_t <- t(snps_num) 

##TODO: Data Frame Creation

snps_num_df <- data.frame(snps_num_t) 

TODO: NA Discovery

##TODO: Find the NAs in the file and display the number

find_NAs <- function(x){
  NAs_TF <- is.na(x)
  i_NA <- which(NAs_TF == TRUE)
  N_NA <- length(i_NA)
  
  cat("Results:",N_NA, "NAs present\n.")
  return(i_NA)
}

##TODO: Displays how many NAs are present in each row

# N_rows
# number of rows (individuals)
N_rows <- nrow(snps_num_t)

# N_NA
# vector to hold output (number of NAs)
N_NA   <- rep(x = 0, times = N_rows)

# N_SNPs
# total number of columns (SNPs)
N_SNPs <- ncol(snps_num_t)

# the for() loop
for(i in 1:N_rows){
  
  # for each row, find the location of
  ## NAs with snps_num_t()
  i_NA <- find_NAs(snps_num_t[i,]) 
  
  # then determine how many NAs
  ## with length()
  N_NA_i <- length(i_NA)
  
  # then save the output to 
  ## our storage vector
  N_NA[i] <- N_NA_i
}
## Results: 28 NAs present
## .Results: 20 NAs present
## .Results: 28 NAs present
## .Results: 24 NAs present
## .Results: 23 NAs present
## .Results: 63 NAs present
## .Results: 51 NAs present
## .Results: 38 NAs present
## .Results: 34 NAs present
## .Results: 24 NAs present
## .Results: 48 NAs present
## .Results: 21 NAs present
## .Results: 42 NAs present
## .Results: 78 NAs present
## .Results: 45 NAs present
## .Results: 21 NAs present
## .Results: 42 NAs present
## .Results: 34 NAs present
## .Results: 66 NAs present
## .Results: 54 NAs present
## .Results: 59 NAs present
## .Results: 52 NAs present
## .Results: 47 NAs present
## .Results: 31 NAs present
## .Results: 63 NAs present
## .Results: 40 NAs present
## .Results: 40 NAs present
## .Results: 22 NAs present
## .Results: 60 NAs present
## .Results: 48 NAs present
## .Results: 961 NAs present
## .Results: 478 NAs present
## .Results: 59 NAs present
## .Results: 26 NAs present
## .Results: 285 NAs present
## .Results: 409 NAs present
## .Results: 1140 NAs present
## .Results: 600 NAs present
## .Results: 1905 NAs present
## .Results: 25 NAs present
## .Results: 1247 NAs present
## .Results: 23 NAs present
## .Results: 750 NAs present
## .Results: 179 NAs present
## .Results: 433 NAs present
## .Results: 123 NAs present
## .Results: 65 NAs present
## .Results: 49 NAs present
## .Results: 192 NAs present
## .Results: 433 NAs present
## .Results: 66 NAs present
## .Results: 597 NAs present
## .Results: 1891 NAs present
## .Results: 207 NAs present
## .Results: 41 NAs present
## .Results: 268 NAs present
## .Results: 43 NAs present
## .Results: 110 NAs present
## .Results: 130 NAs present
## .Results: 90 NAs present
## .Results: 271 NAs present
## .Results: 92 NAs present
## .Results: 103 NAs present
## .Results: 175 NAs present
## .Results: 31 NAs present
## .Results: 66 NAs present
## .Results: 64 NAs present
## .Results: 400 NAs present
## .Results: 192 NAs present
## .Results: 251 NAs present
## .Results: 69 NAs present
## .Results: 58 NAs present
## .

##TODO: Cut off 50% of SNPs and make a histogram of N_NA

# 50% of N_SNPs
cutoff50 <- N_SNPs*0.5

hist(N_NA)            
abline(v = cutoff50, 
       col = 2, 
       lwd = 2, 
       lty = 2)

##TODO: Get a percentage of NA

percent_NA <- N_NA/N_SNPs*100

# Call which() on percent_NA
i_NA_50percent <- which(percent_NA > 50) 

snps_num_t02 <- snps_num_t[-i_NA_50percent, ]

TODO: Assigning our Identification

##TODO: Create our row and names, assigning the data to each

row_names <- row.names(snps_num_t02) # Key

row_names02 <- gsub("sample_","",row_names)

sample_id <- gsub("^([ATCG]*)(_)(.*)",
                  "\\3",
                  row_names02)
pop_id <- gsub("[01-9]*",    
               "",
               sample_id)

table(pop_id)  
## pop_id
## Alt Cau Div Nel Sub 
##  15  12  15  15  11

TODO: Dataframe Processing

##TODO: Omits columns with invar

invar_omit <- function(x){
  cat("Dataframe of dim",dim(x), "processed...\n")
  sds <- apply(x, 2, sd, na.rm = TRUE)
  i_var0 <- which(sds == 0)
 
  
  cat(length(i_var0),"columns removed\n")
  
  if(length(i_var0) > 0){
     x <- x[, -i_var0]
  }
  
  ## add return()  with x in it
  return(x)                      
}


snps_no_invar <- invar_omit(snps_num_t02) 
## Dataframe of dim 68 1929 processed...
## 591 columns removed

TODO: Column Update Accuracy

##TODO: Update the columns and replace NAs

snps_noNAs <- snps_no_invar

N_col <- ncol(snps_no_invar)
for(i in 1:N_col){
  
  # get the current column
  column_i <- snps_noNAs[, i]
  
  # get the mean of the current column
  mean_i <- mean(column_i, na.rm = TRUE)
  
  # get the NAs in the current column
  NAs_i <- which(is.na(column_i))
  
  # record the number of NAs
  N_NAs <- length(NAs_i)

  # replace the NAs in the current column
  column_i[NAs_i] <- mean_i
  
  # replace the original column with the
  ## updated columns
  snps_noNAs[, i] <- column_i
  
}

Save the data

Save the data as a .csv file which can be loaded again later.

write.csv(snps_noNAs, file = "SNPs_cleaned.csv",
          row.names = F)

Check for the presence of the file with list.files()

list.files(pattern = ".csv")
## [1] "dinog.csv"               "SNPs_cleaned.csv"       
## [3] "walsh2017morphology.csv"

Next steps:

In Part 2, we will re-load the SNPs_cleaned.csv file and carry an an analysis with PCA.