R-将dist函数应用于组 [英] R - Apply dist function to groups
问题描述
我正在尝试使用 dist()函数在R中按行排列,但是我得到的结果似乎根本就没有分组,它只是将dist()应用于我的所有数据框.
I am trying to apply the dist() function row wise in R but the result I get is as if it isn't grouping at all, it is simply applying dist() to all of my dataframe.
df2 %>% dplyr::group_by(X1) %>% dist()
df2
是我的数据帧,为简单起见,我现在暂时申请.本质上,每个组都包含坐标(A,B),我正在尝试获取每个点之间的距离.
Where df2
is my dataframe and I am just applying to the head for now, for simplicity. Essentially, each group contains coordinates (A,B) and I am trying to get the distance between each point.
这是我的数据框:
X1 A B
1 1 12 0.0
2 1 18 0.0
3 1 18 1.0
4 1 13 0.0
5 1 18 4.0
6 1 18 0.0
7 1 18 5.0
8 1 18 0.0
9 1 18 0.0
10 2 73 -2.0
11 2 73 -0.5
12 2 74 -0.5
13 2 73 0.0
14 2 71 -1.0
15 2 75 0.0
我想要的输出是每组的下三角矩阵,这是一个示例:
My desired output is the lower triangular matrix of each group, here is an example:
推荐答案
下面是创建物种物种虹膜数据集距离矩阵的示例
Here's an example of creating distance matrices of the iris data set by species
results = list()
for(spec in unique(iris$Species)){
temp = iris[iris$Species==spec, 1:4]
results[[length(results)+1]] = dist(temp)
}
names(results) = unique(iris$Species)
您必须弄清楚如何处理后遗症.
You'll have to figure out what to do with it afterwords.
这篇关于R-将dist函数应用于组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!