I tried to write a similarity matrix by using cosine similarity, and I used nested loop. I know that nested loops are not always idiomatic in R, and this implementation takes a lot of time to execute.
I am wondering how can I convert this code to a code without nested loop.
cosine.sim <- function(data)
{
data <- t(data)
cos.sim <- matrix (data = 1, nrow = ncol(data), ncol = ncol(data))
for(i in 1:(ncol(data)-1))
{
for(j in (i+1):ncol(data))
{
A <- sqrt ( sum (data[,i] ^2) )
B <- sqrt ( sum (data[,j] ^2) )
C <- sum ( data[,i] * data[,j] )
cos.sim [i,j] <- C / (A * B)
cos.sim [j,i] <- C / (A * B)
}
}
return (cos.sim)
}