在R的base/dplyr中,找到与数据集的每一行最接近的行

In R's base/dplyr, find the row closest to each row of a data set

我有一个包含 N 行的数据框,我想为这些行的子集计算属于同一组的数据集中最接近它们的每一行。

例如:

> df
# A tibble: 8,014 x 4
     A      B       C      Group
    <dbl>  <dbl>   <dbl>    <int>
 1  -0.396 -0.621 -0.759      1
 2  -0.451 -0.625 -0.924      1
 3  -0.589 -0.624 -1.26       1
 4  -0.506 -0.625 -1.09       1
 5  NA      1.59  -0.593      1
 6  -0.286  4.22  -0.0952     1
 7  NA      2.91  -0.0952     1
 8  NA      4.22  -0.924      1
 9  -0.175  1.52  -0.0952     1
10  NA      1.74   1.56       1
# ... with 8,004 more rows

因此,例如,我想检查哪些行最接近属于组 ==1 的第 2 行和第 3 行。另外,我必须高效地执行此操作,因此 for 循环并不是一个真正的选择。

我想使用 dist 函数,因为它具有正确处理 NA 的良好特性,但我不需要计算整个距离矩阵 - 这将是一种浪费。

我试过了,但是失败了,而且很浪费:

res = Map(function(x,y) dist(as.matrix(rbind(x, y))), df[2:3, ] 
%>% group_by(Group), df %>% group_by(Group))

一种执行此操作的方法,但它确实为每个组创建了整个距离矩阵。考虑到您正在尝试做的事情,不确定为什么这样做很浪费:

library(tidyverse)
library(purrr)

min_dist <- function(x){

  dist(x, upper = T) %>% 
    as.matrix %>% 
    as.tibble %>% 
    na_if(0) %>%  #as.tibble adds zeros along the diagonal, so this removes them
    summarize_all(funs(which(. == min(.,na.rm=TRUE)))) %>% 
    gather %>% 
    pull(value)
}


df %>% group_by(Group) %>%
  mutate(group_row = row_number()) %>%
  nest(-Group) %>% 
  mutate(nearest_row = map(data, min_dist)) %>% 
  unnest