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

Ben Bolker bbolker at gmail.com
Wed Sep 11 01:48:04 CEST 2013


On 13-09-10 06:24 PM, arun wrote:
> Hi,
> May be this also works:
> 
>  dist(x)
> #   1  2  3
> #2  2      
> #3  6  4   
> #4 12 10  6
> 
> as.matrix(dist(x))
> #   1  2 3  4
> #1  0  2 6 12
> #2  2  0 4 10
> #3  6  4 0  6
> #4 12 10 6  0
> which(dist(x)==min(dist(x)))
> #[1] 1
> A.K.

  Yes, but you need to set the diagonal to NA, or something -- the OP
doesn't want to include self-comparison. It also helps to use
arr.ind=TRUE in which().  You're right that dist() would be a hair more
efficient that outer(...), though

> 
> 
> 
> ----- Original Message -----
> From: Ben Bolker <bbolker at gmail.com>
> To: r-help at stat.math.ethz.ch
> Cc: 
> Sent: Tuesday, September 10, 2013 5:39 PM
> Subject: Re: [R] Subtracting elements of a vector from each other stepwise
> 
> 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]
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list