dplyr R中的欧几里德距离

时间:2015-10-05 09:12:25

标签: r dplyr

如何计算通过某种处理分组的观察之间的距离矩阵。

数据示例:

set.seed(1212)
df <- data.frame(yta = c(rep("A", 3), rep("B", 3)), x = rnorm(6, 10, 2), y = rnorm(6, 40, 12))

我想要获得的输出就像这样

          1         2         3         4         5         6
1            4.234690 25.858459         0         0         0 
2  4.234690           23.503327         0         0         0
3 25.858459 23.503327                   0         0         0
4         0         0         0            9.330203  9.277692
5         0         0         0  9.330203           18.371015
6         0         0         0  9.277692 18.371015      

1 个答案:

答案 0 :(得分:2)

使用splitlapplybind_rows我们可以获得以下内容:

df %>% split(., (.)$yta) %>% lapply(function(df_part) df_part %>% select(-yta) %>% as.matrix %>% 
                                      dist(upper = T) %>% as.matrix %>% as.data.frame) %>% 
  bind_rows %>% mutate(yta = df$yta)

# Source: local data frame [6 x 7]
# 
#           1        2         3        4         5         6 yta
# 1  0.000000 28.43909  4.350409       NA        NA        NA   A
# 2 28.439090  0.00000 32.038712       NA        NA        NA   A
# 3  4.350409 32.03871  0.000000       NA        NA        NA   A
# 4        NA       NA        NA  0.00000 20.267301 29.106135   B
# 5        NA       NA        NA 20.26730  0.000000  9.116934   B
# 6        NA       NA        NA 29.10614  9.116934  0.000000   B