Question: Need the R code for the following problem. Write a function called `cosine_distance` that takes two arguments: * `x1`: a vector containing the numerical characteristics
Need the R code for the following problem.
Write a function called `cosine_distance` that takes two arguments:
* `x1`: a vector containing the numerical characteristics of individual 1 (perhaps money spent on each of 20 different categories of products) * `x2`: a vector containing the numerical characteristics of individual 2
The function should return the "cosine distance" between them. Schematically (part of your task is to figure out how to write this in R), the equation for the cosine distance between vectors `x1` and `x2` is:
`d = 1 - (x1[1]*x2[1]+x1[2]*x2[2]+x1[3]*x2[3]+...)/( sqrt(x1[1]^2+x1[2]^2+x1[3]^2+...)*sqrt(x2[1]^2+x2[2]^2+x2[3]^2+ ...) )`
For example, if `x1 <- c(4,9,3)` and `x2 <- c(1,7,5)` then
`d = 1 - (4*1 + 9*7 + 3*5)/( sqrt(4^2+9^2+3^2)*sqrt(1^2+7^2+5^2) ) = 0.08033367`
Have your function give a warning if the number of elements in `x1` is different than the number of elements in `x2` that says "Both vectors need to have the same number of elements for calculation to make sense!".
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
