-
Notifications
You must be signed in to change notification settings - Fork 0
/
Stats.r
62 lines (53 loc) · 2.26 KB
/
Stats.r
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
options(repos = c(CRAN = "https://cran.r-project.org"))
packages <- c("vcfR","ggplot2", "dplyr", "tidyr", "reshape", "StAMPP", "adegenet", "corrplot")
# Check if packages are installed
installed_packages <- packages %in% rownames(installed.packages())
# Install packages that are not installed
if (any(!installed_packages)) {
install.packages(packages[!installed_packages])
}
library(tidyr)
library(vcfR)
library(adegenet)
library(StAMPP)
library(ggplot2)
library(corrplot)
library(reshape)
args = commandArgs(trailingOnly=TRUE)
########### Create stats directory #################
dir.create("03_Analysis/05_stats", showWarnings = T)
dir.create("03_Analysis/05_stats/01_PCA", showWarnings = T)
##running PCA
snp_vcf2 = read.vcfR(args[1])
pop.data2 = read.table(args[2], header = F)
gl.snp2 <- vcfR2genlight(snp_vcf2)
pop(gl.snp2) <- rep(pop.data2$V2)
snp.pca2 <- glPca(gl.snp2, nf = 10)
##write PCA scores
snp.pca.scores2 <- as.data.frame(snp.pca2$scores)
snp.pca.scores2$pop <- pop(gl.snp2)
PCA_adegen_path <- file.path("03_Analysis/05_stats/01_PCA", paste(args[3], "adegenetPCA.txt", sep = "_"))
write.table(snp.pca.scores2, PCA_adegen_path, sep = "\t")
##export list of eigen values and percentage variances for each PC
#eigen values for PCs
eig.val<-snp.pca2$eig
eig.val
#percentages of variance for each PC
eig.perc <- 100*snp.pca2$eig/sum(snp.pca2$eig)
eig.perc
eigen<-data.frame(eig.val,eig.perc)
eigen
#writing file with both
PCA_eigen_path <- file.path("03_Analysis/05_stats/01_PCA", paste(args[3], "eigen_summary.txt", sep = "_"))
write.csv(eigen,file=PCA_eigen_path,row.names=TRUE,quote=FALSE)
##PCA plotting
data2 = read.delim(PCA_adegen_path) #I have manually added population information to this file prior to loading it
mycol = c("#f1c039", "#f37d21", "#51692d", "#56ba32", "#2b83ba", "#e41a1c", "#02ccf5", "#4daf4a")
ggplot(data2, aes(x=PC1, y=PC2, color=pop)) +
geom_point(size = 2) +
scale_color_manual(values=mycol) +
theme_classic()+
xlab(paste("PC1 (", round(100 * snp.pca2$eig[3] / sum(snp.pca2$eig), 2), "%)", sep = "")) +
ylab(paste("PC2 (", round(100 * snp.pca2$eig[4] / sum(snp.pca2$eig), 2), "%)", sep = ""))
PCA_plot_output <- "03_Analysis/05_stats/01_PCA"
ggsave(path = PCA_plot_output, filename = paste(args[3], "PCAplot.png", sep = "_"), device='png', dpi=1000)