[R] Efficient way to substract all entries in two vectors from each other

Talbot Katz topkatz at msn.com
Mon Jan 7 19:01:20 CET 2008


Hi Joh.

To echo Bert, more detail would be helpful.  But here is a stab at something.  Given two numeric vectors, a and b, for each entry of a this finds the index in b of the closest match.  It's not efficient at all.

> bestmati <- function( a, b ) { return( sapply( a, function( x ) { which.min( ( b - x )^2 ) } ) ) }
> bestmati( c( 3, 9 ), c( 1, 4, 2, 6, 7, 5 ) )
[1] 2 5
>

--  TMK  --
212-460-5430	home
917-656-5351	cell
t o p k a t z @ m s n . c o m




More information about the R-help mailing list