VOOZH about

URL: https://www.geeksforgeeks.org/r-language/how-to-calculate-cosine-similarity-in-r/

⇱ How to Calculate Cosine Similarity in R? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Calculate Cosine Similarity in R?

Last Updated : 28 Nov, 2021

In this article, we are going to see how to calculate Cosine Similarity in the R Programming language.

We can define cosine similarity as the measure of the similarity between two vectors of an inner product space. The formula to calculate the cosine similarity between two vectors is:

where

  • X is the first vector
  • Y is the second vector

We can calculate this by using the cosine() function, Thus the function is available in the module called lsa. so we have to load that module first.

Syntax: cosine(X,Y)

where

  1. X is the first vector
  2. Y is the second vector

Example: R program to calculate the cosine similarity between two vectors

Output:

[,1]
[1,] 0.5468596

Example 2: R program to calculate cosine similarity in a matrix

Output:

 vector1 vector2 vector3
vector1 1.0000000 0.5468596 0.5468596
vector2 0.5468596 1.0000000 1.0000000
vector3 0.5468596 1.0000000 1.0000000

Note:

  • This function will not work on dataframes, You have to convert dataframe into the matrix to get the result.
  • This function will work only on square matrices.
Comment
Article Tags:

Explore