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

Cosine similarity measures the cosine of the angle between two non-zero vectors, providing a metric that quantifies how similar the vectors are.

In this article, we will explore how to calculate cosine similarity in R using the cosine() function.

Method: Use cosine() Function

The cosine() function in R is used to calculate the cosine similarity between vectors or matrices. Here’s the syntax:

library(lsa)

cosine(a, b)
  • a, b: Vectors or matrices

The following examples show how to calculate cosine similarity using the cosine() function in R.

Use cosine() to Calculate Cosine Similarity Between Vectors

Let’s see how to calculate cosine similarity using the 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
similarity <- cosine(a, b)

# Display cosine similarity
print(similarity)

Output: 👇️

          [,1]
[1,] 0.9982161

In this example, the cosine() function calculates the cosine similarity between vectors 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
similarity_matrix <- cosine(matrix1)

# Display cosine similarity matrix
print(similarity_matrix)

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

In this example, the cosine() function calculates the cosine similarity between the columns of the matrix matrix1.