[R] Getting rid of loops?

Peter Dalgaard p.dalgaard at biostat.ku.dk
Wed Dec 3 00:57:46 CET 2003


Simon.Gatehouse at csiro.au writes:

> I think this will do what you want, though there may be ways of speeding it
> up further.
> 
> theta.dist <- function(x)
> as.dist(acos(crossprod(t(x))/sqrt(crossprod(t(rowSums(x*x)))))/pi*180)

Or,

theta.dist <- function(x)
  as.dist(acos(cov2cor(crossprod(t(x))))/pi*180)

Now, if only there was a way to tell cor() not to center the
variables, we'd have 

  as.dist(acos(cor(t(x),center=F))/pi*180)

Unfortunately there's no such argument.

> 
> 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)
> }
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://www.stat.math.ethz.ch/mailman/listinfo/r-help
> <https://www.stat.math.ethz.ch/mailman/listinfo/r-help> 
> 
> 
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://www.stat.math.ethz.ch/mailman/listinfo/r-help
> 

-- 
   O__  ---- Peter Dalgaard             Blegdamsvej 3  
  c/ /'_ --- Dept. of Biostatistics     2200 Cph. N   
 (*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: (+45) 35327907




More information about the R-help mailing list