这个问题是如何从距离矩阵中提取组内和组间距离的后续问题?在 R 中。在那个问题中,他们首先计算了所有点的距离矩阵,然后简单地提取了类间距离矩阵。我有一种情况,我想绕过初始计算并直接跳到提取,即我想直接计算类间距离矩阵。从链接的示例中提取,经过调整,假设我在一个名为的数据框中有一些数据df
:
values<-c(0.002,0.3,0.4,0.005,0.6,0.2,0.001,0.002,0.3,0.01)
class<-c("A","A","A","B","B","B","B","A","B","A")
df<-data.frame(values, class)
我想要的是一个距离矩阵:
1 2 3 8 10
4 .003 .295 .395 .003 .005
5 .598 .300 .200 .598 .590
6 .198 .100 .200 .198 .190
7 .001 .299 .399 .001 .009
9 .298 .000 .100 .298 .290
R 中是否已经存在一种优雅而快速的方法来做到这一点?
编辑在收到上述一维案例的良好解决方案后,我想到了一个额外的问题:更高维的案例怎么样,如果df
看起来像这样:
values1<-c(0.002,0.3,0.4,0.005,0.6,0.2,0.001,0.002,0.3,0.01)
values2<-c(0.001,0.1,0.1,0.001,0.1,0.1,0.001,0.001,0.1,0.01)
class<-c("A","A","A","B","B","B","B","A","B","A")
df<-data.frame(values1, values2, class)
而且我有兴趣再次获得 classB
中的点与class 中的点之间的欧几里得距离矩阵A
。