Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
303 views
in Technique[技术] by (71.8m points)

compute all pairwise differences within a vector in R

There are several posts on computing pairwise differences among vectors, but I cannot find how to compute all differences within a vector.

Say I have a vector, v.

v<-c(1:4)

I would like to generate a second vector that is the absolute value of all pairwise differences within the vector. Similar to:

abs(1-2) = 1
abs(1-3) = 2
abs(1-4) = 3
abs(2-3) = 1
abs(2-4) = 2
abs(3-4) = 1

The output would be a vector of 6 values, which are the result of my 6 comparisons:

output<- c(1,2,3,1,2,1)

Is there a function in R that can do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
as.numeric(dist(v))

seems to work; it treats v as a column matrix and computes the Euclidean distance between rows, which in this case is sqrt((x-y)^2)=abs(x-y)

If we're golfing, then I'll offer c(dist(v)), which is equivalent and which I'm guessing will be unbeatable.

@AndreyShabalin makes the good point that using method="manhattan" will probably be slightly more efficient since it avoids the squaring/square-rooting stuff.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...