Fw: Summary for [R] Distance matrix by cosine?

Petra Steiner steinep at uni-muenster.de
Fri Jan 25 23:33:12 CET 2002


Dear all,

below you find enclosed my message from January 9th and my program
(attention: beginner).
Thanks for both answers!  a. However, as far as I know the cosine is not the
same as the Pearson correlation (only in special cases).
b. Reid Huntsinger's hint was very useful, however I had to transpose the
matrix first, for I want to calculate the distance of the _rows_.

Regards,
Petra Steiner



#Funktion: Berechnung der Distanzmatrix mit dem Kosinus als Abstandsmass

library(Matrix)

normalize <- function(ma) {
# zunaechst werden die Zeilen der Matrix normalisiert

   nreihe <- nrow(ma)
   nspalte <- ncol(ma)
   print(nspalte)
   c <- matrix(NA, nreihe, nspalte)
   row.names(c) <- row.names(ma)
   colnames(c) <- colnames(ma)
   for (i in 1:nreihe)
   {
    print(i)
     normrow <- norm(ma[i,],"F")
     for (j in 1:nspalte)
    {
        c[i,j] <-ma[i,j]/normrow
    }
   }
   print(c)
   return (c)
 }

# und somit ist der Cosinus identisch mit dem Skalarprodukt
# and thus the Cosine is identical to the inner product

   distmatrix_cos <- function(c) {
  d <- crossprod(t(c))
   row.names(d) <- row.names(c)
   colnames(d) <- row.names(c)

  return(d)
 }

# Hauptprogramm/ Main program

library(mva)
tab <- read.table("C:/Programme/Perl/index/tabelle", header=TRUE)
n <- normalize(tab)
dista <- distmatrix_cos(n)
distanz <- as.dist(dista)

etc.

----- Original Message -----
From: Petra Steiner
To: r-help at lists.r-project.org
Sent: Wednesday, January 09, 2002 11:13 PM
Subject: [R] Distance matrix by cosine?


Hello,

a. is there a possibility to obtain a distance matrix with the cosine
between vectors?? hclust, hierclust, dist will not work and seem to be hard
to extend.

b. if there is not: Is the cosine between vectors implemented somewhere?

Thanks for all hints and advice!

Petra Steiner

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list