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)    
## 
##    *****       ***   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-4
library(ggplot2)
library(ggpubr)

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

getwd()
## [1] "/Users/akashpatel/Desktop/Computational Biology Code:Screenshots"
list.files()
##  [1] "07-mean_imputation.docx"                                                    
##  [2] "07-mean_imputation.html"                                                    
##  [3] "07-mean_imputation.Rmd"                                                     
##  [4] "08-PCA_worked.html"                                                         
##  [5] "08-PCA_worked.Rmd"                                                          
##  [6] "09-PCA_worked_example-SNPs-part1.Rmd"                                       
##  [7] "1.159051856-159301856.ALL.chr1_GRCh38.genotypes.20170504.vcf.gz"            
##  [8] "1000genomes_people_info2-1.csv"                                             
##  [9] "all_loci.vcf"                                                               
## [10] "allomtery_3_scatterplot3d (1).Rmd"                                          
## [11] "bird_snps_remove_NAs.html"                                                  
## [12] "bird_snps_remove_NAs.Rmd"                                                   
## [13] "center_function.R"                                                          
## [14] "cluster_analysis_portfolio.Rmd"                                             
## [15] "code_checkpoint_vcfR.html"                                                  
## [16] "code_checkpoint_vcfR.Rmd"                                                   
## [17] "Comp Bio Test 3.Rmd"                                                        
## [18] "feature_engineering_intro_2_functions-part2.Rmd"                            
## [19] "feature_engineering.Rmd"                                                    
## [20] "Final Project.Rmd"                                                          
## [21] "FinalProject14.27608412-27848412.ALL.chr14_GRCh38.genotypes.20170504.vcf"   
## [22] "FinalProject14.27608412-27848412.ALL.chr14_GRCh38.genotypes.20170504.vcf.gz"
## [23] "fst_exploration_in_class-STUDENT.html"                                      
## [24] "fst_exploration_in_class-STUDENT.Rmd"                                       
## [25] "Junk.Rmd"                                                                   
## [26] "Loading your VCF final project file into R.Rmd"                             
## [27] "Loading-your-VCF-final-project-file-into-R.html"                            
## [28] "PCA-missing_data.Rmd"                                                       
## [29] "portfolio_ggpubr_intro-2.Rmd"                                               
## [30] "portfolio_ggpubr_log_transformation.Rmd"                                    
## [31] "removing_fixed_alleles.html"                                                
## [32] "removing_fixed_alleles.Rmd"                                                 
## [33] "rsconnect"                                                                  
## [34] "Screen Shot 2022-09-29 at 5.32.05 PM.png"                                   
## [35] "Screen Shot 2022-09-29 at 5.32.27 PM.png"                                   
## [36] "Screen Shot 2022-09-29 at 5.33.34 PM.png"                                   
## [37] "Screen Shot 2022-10-05 at 11.28.51 PM.png"                                  
## [38] "Screen Shot 2022-10-06 at 12.32.06 PM.png"                                  
## [39] "Screen Shot 2022-10-08 at 1.05.27 PM.png"                                   
## [40] "Screen Shot 2022-10-08 at 1.05.33 PM.png"                                   
## [41] "Screen Shot 2022-10-08 at 12.32.11 PM.png"                                  
## [42] "Screen Shot 2022-10-17 at 11.01.25 PM.png"                                  
## [43] "Screen Shot 2022-10-17 at 11.27.24 PM.png"                                  
## [44] "Screen Shot 2022-10-17 at 11.38.48 PM.png"                                  
## [45] "Screen Shot 2022-11-26 at 9.01.14 PM.png"                                   
## [46] "test.html"                                                                  
## [47] "test.Rmd"                                                                   
## [48] "TestOct25.docx"                                                             
## [49] "TestOct25.Rmd"                                                              
## [50] "transpose_VCF_data.html"                                                    
## [51] "transpose_VCF_data.Rmd"                                                     
## [52] "vcf_num_df.csv"                                                             
## [53] "vcf_num_df2.csv"                                                            
## [54] "vcf_num.csv"                                                                
## [55] "vcfR_test.vcf"                                                              
## [56] "vcfR_test.vcf.gz"                                                           
## [57] "vegan_PCA_amino_acids-STUDENT.html"                                         
## [58] "vegan_PCA_amino_acids-STUDENT.Rmd"                                          
## [59] "vegan_pca_with_msleep-STUDENT.html"                                         
## [60] "vegan_pca_with_msleep-STUDENT.Rmd"                                          
## [61] "walsh2017morphology.csv"                                                    
## [62] "working_directory_practice.html"                                            
## [63] "working_directory_practice.Rmd"
list.files(pattern = "vcf")
##  [1] "1.159051856-159301856.ALL.chr1_GRCh38.genotypes.20170504.vcf.gz"            
##  [2] "all_loci.vcf"                                                               
##  [3] "code_checkpoint_vcfR.html"                                                  
##  [4] "code_checkpoint_vcfR.Rmd"                                                   
##  [5] "FinalProject14.27608412-27848412.ALL.chr14_GRCh38.genotypes.20170504.vcf"   
##  [6] "FinalProject14.27608412-27848412.ALL.chr14_GRCh38.genotypes.20170504.vcf.gz"
##  [7] "vcf_num_df.csv"                                                             
##  [8] "vcf_num_df2.csv"                                                            
##  [9] "vcf_num.csv"                                                                
## [10] "vcfR_test.vcf"                                                              
## [11] "vcfR_test.vcf.gz"

Data preparation

TODO: Load

TODO: The data from the vcf file is being loaded in SNP format.

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: Extract

TODO: The SNP format will now be extracted and converted into R-compatible format.

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

TODO: Rotate

TODO: Transposing original VCF file into R dataframe orientation, since we want to make a dataframe.

snps_num_t <- t(snps_num) 

TODO: Once you have the actual dataframe orientation you can make a dataframe

snps_num_df <- data.frame(snps_num_t) 

TODO: Find NAs

TODO: We created a function to find count the amount of NAs in our dataframe. The function will also give us a dataframe that has only the NAs. This could be for imputation or simply removing the NAs.

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: Essentially we are using a for loop to iterate to each row in the dataframe to find the location of NAs. Getting the amount of NAs and saving the amount of NAs to a storage vector.

# 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: We are trying to see if we have quality data, essentially plotting 50% of SNP cutoff.

# 50% of N_SNPs
cutoff50 <- N_SNPs*0.5

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

TODO: Checking if any of our rows have greater than 50% 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: Removing names

TODO: We edited the dataframe so we could get rid of the extra wording like sample, ATG, and 01-9, just to give us the “ALT”, “Nel” row names. Makes it more concise.

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: Remove

TODO: In this function we removed invariant columns because if they existed there is no reason to anaylze that data. Would waste time, and computational speed.

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: Impute

TODO: In columns with NAs that meet the cutoff we replace the NAs with the mean of the current column. This we now have No NAs and can analyze data.

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] "1000genomes_people_info2-1.csv" "SNPs_cleaned.csv"              
## [3] "vcf_num_df.csv"                 "vcf_num_df2.csv"               
## [5] "vcf_num.csv"                    "walsh2017morphology.csv"

Next steps:

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