I need to calculate the hamming distance between an input string and a large string dataset. (All strings in the dataset have the same length of the input string.)
For example, if
input <- "YNYYEY"
dataset <- c("YNYYEE", "YNYYYY", "YNENEN", "YNYYEY")
the hamming distance between input
and each string in dataset
is 1, 1, 3, 0 so the minimum is 0. I have written a function to calculate the hamming distance between two strings:
HD <- function(str1, str2){
str1 <- as.character(str1)
str2 <- as.character(str2)
length.str1 <- nchar(str1)
length.str2 <- nchar(str2)
string.temp1 <- c()
for (i in 1:length.str1){
string.temp1[i] = substr(str1, start=i, stop=i)
}
string.temp2 <- c()
for (i in 1:length.str2){
string.temp2[i] = substr(str2, start=i, stop=i)
}
return(sum(string.temp1 != string.temp2))
}
But the dataset is too big so I need to speed it up, do you have any idea that I can do it quickly? Thank you for your help.