[R] vector angle

Prof Brian Ripley ripley at stats.ox.ac.uk
Tue Jul 17 10:17:52 CEST 2001


On Tue, 17 Jul 2001, Laurent Gautier wrote:

> Evan Zane Macosko wrote:
>
> > Hi everyone,
> >
> > I'm translating into R some programs I worked through in Matlab to
> > calculate the angle between two vectors (very large--like 6200 rows in
> > each vector).  In Matlab, I used a series of nested for loops, because I
> > was calculating the angles between many pairs of vectors.  I know for
> > loops are not desirable in R code, so I was wondering if anyone could
> > recommend a faster way to complete this task.  Also, I have NAs in my
> > vectors--I've had trouble performing various operations on my vectors in R
> > because of these NAs.
> >
> > Any advice on this would be greatly appreciated.
>
> As far as I know, the use of apply (sapply and lapply) would make things run
> faster than 'for' loops.

Not very much faster in R (and apply itself is basically a for loop).
Because for loops were slow in S3, the message seems to have got
transferred to S4 and R.  Often the best approach is to see if a loop is
fast enough, first.  (In S-PLUS 5.0 lapply was actually slower than a for
loop.)

The key to speed is usually vectorization (often at the expense of
memory, but these are not very large vectors).  Here it looks as if
outer() might be the key.

I am not clear what is really required here, but if you want the
angles between all pairs of p vectors of length m, say, I would
try

- normalizing them to unit length
- using dist() to compute the Euclidean distances between the pairs,
  since for unit-length vectors x and y ||x - y||^2 = 2 - 2x.y
  = 2(1 - cos th) where th is the angle between them.

That just makes use of for loops written in the C internals of dist,
and doing the computations oneself in C is often a fairly simple option.

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272860 (secr)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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