[R] vectorize an expression

Prof Brian Ripley ripley at stats.ox.ac.uk
Tue May 25 15:14:57 CEST 2004


Suggestion 1: Use the R function `dist'.

Suggestion 2: Don't mask an R system function name.

Suggestion 3: Time this.  I don't think it is worth vectorizing.

Suggestion 4: The bit which is actually nonvectorized is your function 
dist.  If you had a vectorized distance function, you could do

for(i in 1:5) array[i,] <- dist(a[i,,drop=FALSE] , a)

but that would need

dist <- function(x1,x2) sqrt(rowSums(x1-x2)^2)

I could tell you how to fully vectorize it, but I doubt if it would have 
any benefit.

(None of this is tested, because of 1 and 3.)

On Tue, 25 May 2004, Robin Hankin wrote:

> Hi guys.  Another thing I cannot vectorize:
> 
> I have an array "a", of size 5-by-2, for example, of 5 2D vectors.  I
> also have a distance function that computes the distance between two
> vectors (usual Euclidean distance is a good example but I have other metrics I
> want to use as well).  I want a 5-by-5 array with the [i,j]th element being
>   the distance from a[i,] to a[j,]
> 
> To Wit:
> 
>    a <- matrix(1:10,5,2)
>    array <- matrix(NA, 5, 5)
>    dist <- function(x1,x2){sqrt(sum(x1-x2)^2)}
> 
>    #NONVECTORIZED BIT FOLLOWS
>    for(i in 1:5) {
>      for(j in 1:5) {
>        array[i,j] <- dist(a[i,] , a[j,])
>      }
>    }
> 
> (note that array[i,i]=0 for i=1:5 as expected).
> 
> How to vectorize this?
> 
> 
> 

-- 
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 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595




More information about the R-help mailing list