create a matrix by applying user defined function to a set of vectors

Viewed 32

I have this function to measure the similarity of a pair of dictionaries.

similarity_index <- function(dix1, dix2) {
  nc <- length(intersect(dix1,dix2)) 
  n1 <- length(dix1) 
  n2 <- length(dix2)
  return(nc / sqrt(n1*n2))
}

dix1 = c("a","b","c")
dix2 = c("e","f","g")
dix3 = c("a","f","g")

similarity_index(dix1,dix2)
similarity_index(dix2,dix3)
similarity_index(dix1,dix3)

Is there a simple way I can create a matrix by crossing these dictionaries with my function? I'm looking for a dix / dix matrix (in this case 3 rows by 3 cols), like this:

          dix1  dix2  dix3
dix1    1       0       0,3
dix2    0       1       0,6
dix3    0,3   0,6     1

I'll later use this matrix for hclustering or corplot.

1 Answers

We can use outer

v1 <- paste0('dix', 1:3)
out <- outer(v1, v1, Vectorize(function(x, y) similarity_index(get(x), get(y))))
dimnames(out) <- list(v1, v1)
out
#          dix1      dix2      dix3
#dix1 1.0000000 0.0000000 0.3333333
#dix2 0.0000000 1.0000000 0.6666667
#dix3 0.3333333 0.6666667 1.0000000
Related