[R] Subtracting elements of a vector from each other stepwise

Ben Bolker bbolker at gmail.com
Tue Sep 10 23:39:10 CEST 2013


arun <smartpink111 <at> yahoo.com> writes:

> 
> Hi,
> Not sure this is what you wanted:
> 
>  sapply(seq_along(x), function(i) {x1<- x[i]; x2<- x[-i];
x3<-x2[which.min(abs(x1-x2))];c(x1,x3)})
> #     [,1] [,2] [,3] [,4]
> #[1,]   17   19   23   29
> #[2,]   19   17   19   23
> A.K.


  It's a little inefficient (because it constructs
the distances in both directions), but how about:

x = c(17,19,23,29)
d <- abs(outer(x,x,"-"))
diag(d) <- NA
d[lower.tri(d)] <- NA
which(d==min(d,na.rm=TRUE),arr.ind=TRUE)


?
 
> ----- Original Message -----
> From: Michael Budnick <mbudnick08 <at> snet.net>
> To: r-help <at> r-project.org
> Cc: 
> Sent: Tuesday, September 10, 2013 4:06 PM
> Subject: [R] Subtracting elements of a vector from each other stepwise
> 
> I am trying to figure out how to create a loop that will take the
> difference of each member of a vector from each other and also spit out
> which one has the least difference.
> 
> I do not want the vector member to subtract from itself or it must be able
> to disregard the 0 obtained from subtracting from itself.
> 
> For example:
> 
> x = c(17,19,23,29)


 [snip]



More information about the R-help mailing list