How to input self-defined distance function in R? I want to know how to to input a self-defined distance in R, in hierarchical clustering analysis. R implements only some default distance metrics, for example "Euclidean", "Manhattan" etc. Suppose I want to input a self-defined distance '1-cos(x-y)'. Then what should I do?
Writing a function is obviously a solution. But, it will be quite complicated, and also difficult to write. Please help me. I am unable to write the code.
 A: hclust() takes a distance matrix, which you can construct yourself, doing the calculations in R or reading them in from elsewhere.  as.dist() can be used to convert an arbitrary matrix into a 'dist' object, which is a convenient representation  of a distance matrix that hclust() understands.   Obviously whether your own distances make any sense is another question, but it's easy to try out. 
If you want to apply an arbitrary function to all pairs of X and Y to get a matrix, have a look at outer()
A: Have a look at proxy, it creates distance matrices from any custom function.
set.seed(1)
mat <- matrix(runif(5))
fn <- function(x, y) 1 - cos(x - y)

proxy::dist(mat, method = fn)

                1           2           3           4
2 0.005678023                                    
3 0.046859766 0.020078605                        
4 0.199519068 0.140284488 0.055706274            
5 0.002036234 0.014490103 0.068096902 0.239378143

A: My approach is to write the distance function for two vectors and use the apply function to calculate distance to pairs of vectors (stored in a data frame, for example). Convert this symmetric matrix to a dist object using as.dist(). 
hclust() takes a dist object as an argument.
If you're plotting a heatmap, or something, supplying your custom function to the distfun argument overrides the default.
