Created
March 25, 2015 12:59
-
-
Save tkowalczyk/fb912e475adcf0f3ad7c to your computer and use it in GitHub Desktop.
#How to calculate Euclidean Distance in R?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#How to calculate Euclidean Distance in R? | |
print("How to calculate Euclidean Distance in R?") | |
fa <- c(5,2,1,4) | |
fb <- c(5,5,4,2) | |
fm <- matrix(c(fa,fb), byrow=T, nrow=2) | |
col_names_vectors <- c("U1", "U2", "U3", "U4") | |
row_names_vectors <- c("FilmA","FilmB") | |
colnames(fm) <- col_names_vectors | |
rownames(fm) <- row_names_vectors | |
fm | |
#Euclidean Distance based on matrix | |
#Distance from user1 (U1) to the new user | |
d1 <- sqrt((fm[1,1]-fm[1,4])^2 + (fm[2,1]-fm[2,4])^2) | |
d1 | |
#Distance from user2 (U2) to the new user | |
d2 <- sqrt((fm[1,2]-fm[1,4])^2 + (fm[2,2]-fm[2,4])^2) | |
d2 | |
#Distance from user3 (U3) to the new user | |
d3 <- sqrt((fm[1,3]-fm[1,4])^2 + (fm[2,3]-fm[2,4])^2) | |
d3 | |
distance_vector <- c(d1,d2,d3) | |
#Checking which distance is the smallest one | |
min(distance_vector) | |
#For the new user, system should recommend user1 (U1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment