Re: [R] vectorize an expression

About this list Date view Thread view Subject view Author view Attachment view

From: Gabor Grothendieck (ggrothendieck@myway.com)
Date: Tue 25 May 2004 - 21:42:17 EST


Message-id: <loom.20040525T133819-792@post.gmane.org>


apply(a,1,function(y)apply(a,1,function(x)dist(x,y)))

Robin Hankin <rksh <at> soc.soton.ac.uk> writes:

:
: 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?
:

______________________________________________
R-help@stat.math.ethz.ch mailing list
https://www.stat.math.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html


About this list Date view Thread view Subject view Author view Attachment view

This archive was generated by hypermail 2.1.3 : Mon 31 May 2004 - 23:05:12 EST