Load Libraries

# Load libraries
library(GenomeInfoDb)
library(UniprotR)
library(Biostrings)
library(ggmsa)
library(seqinr)
library(forcats)
library(ggplot2)
library(dplyr)
library(tidyverse)

Create Function

comparative_PairwiseAlignment <- function(ref_accession_id, query_accession_ids){

## Clean up Subject sequence
#Get the Sequence for the Subject
Subject_df <-GetSequences(ref_accession_id)

#Retrieve the sequence from dataframe, converting it to a list and assign it a name equivalent to the Uniprot ID
Subject_seq <- list(Subject_df$Sequence)
names(Subject_seq) <- row.names(Subject_df)

#Convert to an AAStringSet object by listing and then unlisting 
Subject_AA <-AAStringSetList(Subject_seq)
Subject_AA_unlisted <- unlist(Subject_AA)

## Clean up Pattern sequences
#Get the Sequences for the Patterns (query sequences)
Pattern_df <- GetSequences(query_accession_ids)

#Retrieve Subject sequences from dataframe and split to a list using regular expression
Pattern_seqs<- Pattern_df$Sequence

#Pattern_seqs_split<-strsplit(Pattern_seqs,'[:digit:]')

# Assign it a name equivalent to the Uniprot ID
names(Pattern_seqs) <- row.names(Pattern_df)

#Convert to an AAStringSet object by listing and then unlisting
Pattern_AA<-AAStringSetList(Pattern_seqs)
Pattern_AA_unlisted<-unlist(Pattern_AA)
names(Pattern_AA_unlisted)<-names(Pattern_seqs)

##Pairwise Alignments
# Local Pairwise Sequence Alignment
local_seq_aln<-sapply(Pattern_AA_unlisted, pairwiseAlignment, Subject_AA_unlisted, type = "local", substitutionMatrix = "BLOSUM50", scoreOnly = FALSE)

# Retrieve scores
local_aln_scores <- c()
for (i in 1:length(local_seq_aln)){
  local_aln_scores[i] <- score(local_seq_aln[[i]])
  }
# Compute Percent Identity (PID)
pid_local <-round(sapply(local_seq_aln, pid, type = "PID3"),2)

#Global Pairwise Sequence Alignment
Global_seq_aln<-sapply(Pattern_AA_unlisted,pairwiseAlignment, Subject_AA_unlisted, type = "global", substitutionMatrix = "BLOSUM50", scoreOnly = FALSE)

# Retrieve scores
Global_aln_scores <- c()
for (i in 1:length(Global_seq_aln)){
  Global_aln_scores[i] <- score(Global_seq_aln[[i]])
  }
# Compute Percent Identity (PID)
pid_Global <-round(sapply(Global_seq_aln, pid, type = "PID3"),2)

## Create and clean Data frame of scores and PID proportion
aln_df<-data.frame(Global_aln_scores, pid_Global,local_aln_scores, pid_local)
aln_df$Accession_ID <- row.names(aln_df) #Creates a column for the accession ids
aln_df<-aln_df %>% relocate(Accession_ID) #relocates accession id column from last to first column
colnames(aln_df)[2:5] <- c("Global_Aln_Score", "Global_PID", "Local_Aln_Score", "Local_PID") #Renames the last 4 columns
df_sorted<-aln_df[order(pid_local),] #Ranks the df by pid from lowest to highest
rownames(df_sorted)<- 1:nrow(df_sorted) #Changes the rownames from accession id to numbering

## Create plot of Local and Global alignment PID
aln_plot<-df_sorted[,c("Accession_ID", "Global_PID", "Local_PID")] %>%
  pivot_longer(cols = "Global_PID":"Local_PID", names_to = "PID", values_to = "percent_identity") %>% 
  mutate(Accession_ID = fct_reorder(Accession_ID,desc(percent_identity))) %>%
  ggplot(aes(x = Accession_ID, y = round((percent_identity/100),2), fill = PID))+
  geom_col(alpha = 0.6, width = 0.7, position=position_dodge2(preserve = "single"))+
  coord_flip()+
  theme_minimal()+
  theme(plot.title = element_text(hjust = 0.5, size = 10))+
  labs(title = "Percent Identity plot of Local and Global Pairwise alignment of Query sequences against Reference",
       y = "Proportion of Percent Identity",
       x = "Query accession ID")

  return(list(df_sorted, aln_plot))
}

Test function

comparative_PairwiseAlignment(ref_accession_id ="W5QDP8", query_accession_ids=c("A0A6P3H9Z6","A0A3Q1MJB2","Q08879","A0A287AL89","P23142"))
## Please wait we are processing your accessions ...
## Please wait we are processing your accessions ...
## [[1]]
##   Accession_ID Global_Aln_Score Global_PID Local_Aln_Score Local_PID
## 1       Q08879             4267      82.65            4305     82.08
## 2       P23142             4364      85.78            4404     85.21
## 3   A0A287AL89             4147      90.75            4618     89.47
## 4   A0A3Q1MJB2             4697      93.03            4744     92.60
## 5   A0A6P3H9Z6             4598      95.85            4708     95.85
## 
## [[2]]