[R] Efficient way to Calculate the squared distances for a set of vectors to a fixed vector

Wei Wu wuwei_10003 at yahoo.com
Wed Aug 24 07:18:05 CEST 2011


I am pretty new to R. So this may be an easy question for most of you.
 
I would like to calculate the squared distances of a large set (let's say 20000) of vectors (let's say dimension of 5) to a fixed vector.
 
Say I have a data frame MY_VECTORS with 20000 rows and 5 columns, and one 5x1 vector y. I would like to efficiently calculate the squared distances between each of the 20000 vectors in MY_VECTORS and y.
 
The squared distance between two vectors x and y can be calculated:
distance <- crossprod(x-y)
 
Without looping, what is the efficient code to achieve this?
 
Thanks.



More information about the R-help mailing list