# distance matrix - mixed variables

HI,
I have a large data set (5000*10).
some columns are categorical and some are continuous.
I want to create a distance function that will treat different columns differently.
let's say that if the column is categorical the distance will be 0 if categories in 2 observations are equal and 1 otherwise.
and for continuous variables, I will calculate the regular euclidian distance between rows.
What is the best wat to implement this?

I am open to hearing other distances option for continuous or categorical variables.

``````

compare_row <- function(row_a,row_b){
row_a_cats <-  select_if(row_a,~!is.numeric(.))
row_b_cats <-  select_if(row_b,~!is.numeric(.))
row_a_nums <-  select_if(row_a,is.numeric)
row_b_nums <-  select_if(row_b,is.numeric)

nums_euclid <- dist(x=as.matrix(union(row_a_nums,row_b_nums)),
method="euclidean") %>% as.numeric()

cats_diff <- sum(purrr::map2_lgl(.x=row_a_cats,
.y=row_b_cats,
.f=~.x!=.y))
sum(nums_euclid,cats_diff,0,na.rm = TRUE)
}

a<-list("a","b",1,2,3,2) %>% as.data.frame() %>% set_names(letters[1:6])
b<-list("a","b",3,2,3,4) %>% as.data.frame() %>% set_names(letters[1:6])
c<-list("c","a",3,2,3,4) %>% as.data.frame() %>% set_names(letters[1:6])

compare_row(a,b)
compare_row(b,c)
compare_row(a,c)``````
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.