简体   繁体   English

计算R中向量内的所有成对差异

[英]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。

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: 输出将是6个值的向量,这是我的6次比较的结果:

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

Is there a function in R that can do this? R中有一个可以做到这一点的功能吗?

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((xy)^2)=abs(xy) 它将v视为列矩阵并计算行之间的欧几里德距离,在本例中为sqrt((xy)^2)=abs(xy)

If we're golfing, then I'll offer c(dist(v)) , which is equivalent and which I'm guessing will be unbeatable. 如果我们正在打高尔夫球,那么我将提供c(dist(v)) ,这是相同的,我猜测它将是无与伦比的。

@AndreyShabalin makes the good point that using method="manhattan" will probably be slightly more efficient since it avoids the squaring/square-rooting stuff. @AndreyShabalin指出,使用method="manhattan"可能会稍微提高效率,因为它避免了平方/平方根的东西。

Let's play golf 我们打高尔夫球吧

abs(apply(combn(1:4,2), 2, diff))

@Ben, yours is a killer! @Ben,你的杀手!

> system.time(apply(combn(1:1000,2), 2, diff))
   user  system elapsed 
   6.65    0.00    6.67 
> system.time(c(dist(1:1000)))
   user  system elapsed 
   0.02    0.00    0.01 
> system.time({
+ v <- 1:1000
+ z = outer(v,v,'-');
+ z[lower.tri(z)];
+ })
   user  system elapsed 
   0.03    0.00    0.03 

Who knew that elegant (read understandable/flexible) code can be so slow. 谁知道优雅(易读易懂/灵活)的代码可能会很慢。

A possible solution is: 可能的解决方案是:

z = outer(v,v,'-'); 
z[lower.tri(z)];

[1] 1 2 3 1 2 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM