setwd("C:/Users/Zachy/OneDrive/Desktop/compbioFall22")
getwd()
## [1] "C:/Users/Zachy/OneDrive/Desktop/compbioFall22"
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.html"                          
##  [7] "09-PCA_worked_example-SNPs-part1.Rmd"                           
##  [8] "10-PCA_worked_example-SNPs-part2.html"                          
##  [9] "10-PCA_worked_example-SNPs-part2.Rmd"                           
## [10] "1000genomes_people_info2-1.csv"                                 
## [11] "21.16015248-16255248.ALL.chr21_GRCh38.genotypes.20170504.vcf.gz"
## [12] "all_loci-1.vcf"                                                 
## [13] "all_loci.vcf"                                                   
## [14] "bird_snps_remove_NAs.html"                                      
## [15] "bird_snps_remove_NAs.Rmd"                                       
## [16] "Chr21_num_df2.csv"                                              
## [17] "Chr21_SNP.vcf"                                                  
## [18] "Chr21_SNP.vcf.gz"                                               
## [19] "DataPrepWorkFlow.Rmd"                                           
## [20] "final_report_template.Rmd"                                      
## [21] "for_pca.csv"                                                    
## [22] "gwas_pheno_env.csv"                                             
## [23] "my_snp.vcf.gz"                                                  
## [24] "pheno.csv"                                                      
## [25] "removing_fixed_alleles.html"                                    
## [26] "removing_fixed_alleles.Rmd"                                     
## [27] "rsconnect"                                                      
## [28] "Screenshot 2022-11-28 082623.jpg"                               
## [29] "SNPs_cleaned.csv"                                               
## [30] "TestPage.html"                                                  
## [31] "TestPage.Rmd"                                                   
## [32] "transpose_VCF_data.html"                                        
## [33] "transpose_VCF_data.Rmd"                                         
## [34] "vcf_num.csv"                                                    
## [35] "vcf_num_df.csv"                                                 
## [36] "vcf_num_df2.csv"                                                
## [37] "vcf_scaled.csv"                                                 
## [38] "walsh2017morphology.csv"                                        
## [39] "working_directory_practice.html"                                
## [40] "working_directory_practice.Rmd"
my_snps<- "Chr21_SNP.vcf.gz"

vcf <- vcfR::read.vcfR(my_snps, convertNA = T)
## Scanning file to determine attributes.
## File attributes:
##   meta lines: 130
##   header_line: 131
##   variant count: 7281
##   column count: 2513
## 
Meta line 130 read in.
## All meta lines processed.
## gt matrix initialized.
## Character matrix gt created.
##   Character matrix gt rows: 7281
##   Character matrix gt cols: 2513
##   skip: 0
##   nrows: 7281
##   row_num: 0
## 
Processed variant 1000
Processed variant 2000
Processed variant 3000
Processed variant 4000
Processed variant 5000
Processed variant 6000
Processed variant 7000
Processed variant: 7281
## All variants processed
vcf_num <- vcfR::extract.gt(vcf,
                            element = "GT",
                            IDtoRowNames = F,
                            as.numeric = T,
                            convertNA = T)

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

vcf_num_t <- t(vcf_num)
vcf_num_df <- data.frame(vcf_num_t)
sample <- row.names(vcf_num_df)
vcf_num_df <- data.frame(sample, vcf_num_df)

write.csv(vcf_num_df,
          file = "vcf_num_df.csv",
          row.names = F)
pop_meta <- read.csv(file = "1000genomes_people_info2-1.csv")

names(pop_meta)
## [1] "pop"       "super_pop" "sample"    "sex"       "lat"       "lng"
names(vcf_num_df)[1:10]
##  [1] "sample" "X1"     "X2"     "X3"     "X4"     "X5"     "X6"     "X7"    
##  [9] "X8"     "X9"
vcf_num_df2 <- merge(pop_meta, 
                     vcf_num_df,
                     by = "sample")
nrow(vcf_num_df) == nrow(vcf_num_df2)
## [1] TRUE
names(vcf_num_df2)[1:15]
##  [1] "sample"    "pop"       "super_pop" "sex"       "lat"       "lng"      
##  [7] "X1"        "X2"        "X3"        "X4"        "X5"        "X6"       
## [13] "X7"        "X8"        "X9"
write.csv(vcf_num_df2, file = "vcf_num_df2.csv", row.names = F)
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) 
}

names(vcf_num_df2)[1:10]
##  [1] "sample"    "pop"       "super_pop" "sex"       "lat"       "lng"      
##  [7] "X1"        "X2"        "X3"        "X4"
vcf_noinvar <- vcf_num_df2

vcf_noinvar[, -c(1:6)] <- invar_omit(vcf_noinvar[, -c(1:6)])
## Dataframe of dim 2504 7281 processed...
## 1746 columns removed
my_meta_N_invar_cols <- 413
find_NAs <- function(x){
  NAs_TF <- is.na(x)
  i_NA <- which(NAs_TF == TRUE)
  N_NA <- length(i_NA)
  
  return(i_NA)
}

N_rows <- nrow(vcf_noinvar)
N_NA <- rep(x = 0, times = N_rows)
N_SNPs <- ncol(vcf_noinvar)

for(i in 1:N_rows){
  i_NA <- find_NAs(vcf_noinvar[i,])
  N_NA_i <- length(i_NA)
  N_NA[i] <- N_NA_i
}

cutoff50 <- N_SNPs*0.5
percent_NA <- N_NA/N_SNPs*100
any(percent_NA > 50)
## [1] FALSE
my_meta_N_meanNA_rows <- mean(percent_NA)


mean_imputation <- function(df){
  cat("This may take some time...")
  n_cols <- ncol(df)
  for(i in 1:n_cols){
    column_i <- df[,i]
    mean_i <- mean(column_i, na.rm = TRUE)
    NAs_i <- which(is.na(column_i))
    N_NAs <- length(NAs_i)
    column_i[NAs_i] <- mean_i
    df[,i] <- column_i
  }
  return(df)
}

names(vcf_noinvar)[1:10]
##  [1] "sample"    "pop"       "super_pop" "sex"       "lat"       "lng"      
##  [7] "X1"        "X2"        "X3"        "X4"
vcf_noNA <- vcf_noinvar
vcf_noNA[, -c(1:6)] <- mean_imputation(vcf_noinvar[, -c(1:6)])
## This may take some time...
vcf_scaled <- vcf_noNA
vcf_scaled[,-c(1:6)] <- scale(vcf_noNA[,-c(1:6)])

write.csv(vcf_scaled, file = "vcf_scaled.csv",
          col.names = T)
## Warning in write.csv(vcf_scaled, file = "vcf_scaled.csv", col.names = T):
## attempt to set 'col.names' ignored
vcf_pca <- prcomp(vcf_scaled[,-c(1:6)])

Plotting for Visual Representation

Below you will visual data representation to allow for a better understanding of the data package being loaded

screeplot(vcf_pca)

PCA_variation <- function(pca_summary, PCs = 2){
  var_explained <- pca_summary$importance[2,1:PCs]*100
  var_explained <- round(var_explained, 3)
  return(var_explained)
}

vcf_pca_summary <- summary(vcf_pca)
var_out <- PCA_variation(vcf_pca_summary, PCs = 500)


N_columns <- ncol(vcf_scaled)
cut_off <- 1/N_columns*100
i_cut_off <- which(var_out < cut_off)
i_cut_off <- min(i_cut_off)
## Warning in min(i_cut_off): no non-missing arguments to min; returning Inf
my_meta_N_meanNA_rowsPCs <- i_cut_off

my_meta_var_PC123 <- var_out[c(1,2,3)]

barplot(var_out,
        main = "Percent variation (%) Scree plot",
        ylab = "Percent variation (%) explained",
        names.arg = 1:length(var_out))
abline(h = cut_off, col = 2, lwd = 2)

abline(v = i_cut_off)
legend("topright",
       col = c(2,1),
       lty = c(1,1),
       legend = c("Vertical line: cutoff",
                  "Horizontal line: 1st value below cut off"))

cumulative_variation <- cumsum(var_out)
plot(cumulative_variation)

vcf_pca_scores <- vegan::scores(vcf_pca)
vcf_pca_scores2 <- data.frame(super_pop = vcf_noNA$super_pop, vcf_pca_scores)

my_meta_var_PC123[1]
##   PC1 
## 3.057
my_meta_var_PC123[2]
##   PC2 
## 1.519
ggpubr::ggscatter(data = vcf_pca_scores2,
                  y = "PC2",
                  x = "PC1",
                  color = "super_pop",
                  shape = "super_pop",
                  main = "PCA Scatterplot",
                  xlab = "PC1 (1.5% of variation)",
                  ylab = "PC2 (1.1% of variation)")

ggpubr::ggscatter(data = vcf_pca_scores2,
                  y = "PC3",
                  x = "PC2",
                  color = "super_pop",
                  shape = "super_pop",
                  main = "PCA Scatterplot",
                  xlab = "PC2 (1.1% of variation",
                  ylab = "PC3 (1.05% of variation)")

ggpubr::ggscatter(data = vcf_pca_scores2,
                  y = "PC3",
                  x = "PC1",
                  color = "super_pop",
                  shape = "super_pop",
                  main = "PCA Scatterplot",
                  xlab = "PC1 (1.5% of variation)",
                  ylab = "PC3 (1.05% of variation")