[R] Getting rid of loops?

Xiao-Jun Ma xma at arcturusag.com
Fri Nov 28 00:01:36 CET 2003


I wrote a function to calculate cosine distances between rows of a matrix.
It uses two loops and is slow. Any suggestions to speed this up? Thanks in
advance.


theta.dist <- function(x){

  res <- matrix(NA, nrow(x), nrow(x))

  for (i in 1:nrow(x)){
    for(j in 1:nrow(x)){
      if (i > j)
        res[i, j] <- res[j, i]
      else {
        v1 <- x[i,]
        v2 <- x[j,]
        good <- !is.na(v1) & !is.na(v2)
        v1 <- v1[good]
        v2 <- v2[good]
        theta <- acos(v1%*%v2 / sqrt(v1%*%v1 * v2%*%v2 )) / pi * 180
        res[i,j] <- theta
      }
    }
  }
  as.dist(res)
}




More information about the R-help mailing list