代码之家  ›  专栏  ›  技术社区  ›  B. Davis

基于最小距离为组指定点

  •  0
  • B. Davis  · 技术社区  · 6 年前

    我试图根据欧几里德距离将点分组。例如,在下面的数据中,有三个点代表三个不同的组( One, Two, Three ,图中的非绿色点)。我想分配剩下的几点( Scatter 根据最小欧几里德距离(即变化)将绿色点)分组 分散 最接近 One Two Three 点数。

    我想在外面做这件事 kmeans 或其他聚类函数和简单使用最小欧氏距离,但欢迎和欣赏的建议。

    set.seed(123)
    Data <- data.frame(
      x = c(c(3,5,8), runif(20, 1, 10)),
      y = c(c(3,5,8), runif(20, 1, 10)),
      Group = c(c("One", "Two", "Three"), rep("Scatter", 20))
    )
    
    ggplot(Data, aes(x, y, color = Group)) +
      geom_point(size = 3) +
      theme_bw()
    

    enter image description here

    1 回复  |  直到 6 年前
        1
  •  2
  •   Maurits Evers    6 年前

    bind_cols(
        Data,
        dist(Data %>% select(-Group)) %>%              # Get x/y coordinates from Data
            as.matrix() %>%                            # Convert to full matrix
            as.data.frame() %>%                        # Convert to data.frame
            select(1:3) %>%                            # We're only interested in dist to 1,2,3
            rowid_to_column("pt") %>%                  
            gather(k, v, -pt) %>%
            group_by(pt) %>%
            summarise(k = k[which.min(v)])) %>%        # Select label with min dist
        mutate(Group = factor(Group, levels = unique(Data$Group))) %>%
        ggplot(aes(x, y, colour = k, shape = Group)) +
        geom_point(size = 3)
    

    enter image description here

    dist 之间 One , Two , Three Scatter 分散 指向标签 k ( k = 1 ), 两个 ( k = 2 ), ( k = 3

    分散 两个 ( k=2个 ); 您可以通过添加 coord_fixed() ggplot 情节链。