To calculate cosine similarity in R, you can use the cosine() function from lsa package.

The following method shows how you can do it with syntax.

Method: Use cosine() Function

library(lsa)

cosine(a,b)

a, b: Vector or matrices

The following example shows how to calculate cosine similarity using cosine() function in R.

Use cosine() to Calculate Cosine Similarity Between Vectors

Let’s see how to calculate cosine similarity using cosine() function in R.

# Load library
library(lsa)

# Define vectors
a <-c(78,85,89,96,74,75)
b <-c(65,66,64,69,70,61)

# Calculate cosine similarity
cosine(a,b)

Output:

          [,1]
[1,] 0.9982161

The output shows cosine similarity between vector a and b.

Use cosine() to Calculate Cosine Similarity Between Matrices

Let’s see how we can calculate cosine similarity between matrices in R:

# Load library
library(lsa)

# Define vectors
a <-c(78,85,89,96,74,75)
b <-c(65,66,64,69,70,61)
c <-c(23,25,26,19,21,18)
d <-c(45,41,35,36,39,48)

# Define matrix
matrix1 <- cbind(a,b,c,d)

# Calculate cosine similarity
cosine(matrix1)

Output:

  a         b         c         d
a 1.0000000 0.9954716 0.9890725 0.9812092
b 0.9954716 1.0000000 0.9898941 0.9893902
c 0.9890725 0.9898941 1.0000000 0.9790813
d 0.9812092 0.9893902 0.9790813 1.0000000

As the output shows cosine similarity between matrices in R.