【问题标题】:Assign points to a group based on minimum distance根据最小距离将点分配给组
【发布时间】:2019-02-20 21:55:50
【问题描述】:

我正在尝试根据欧几里得距离将点分配到分组中。例如,在下面的数据中,三个点代表三个不同的组(One, Two, Three,图中的非绿色点)。我想将剩余的点(Scatter 绿点)分配到基于最小欧几里得距离的分组中(即将Scatter 更改为最接近的OneTwoThree 点。

我试图在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()

【问题讨论】:

    标签: r ggplot2 distance k-means


    【解决方案1】:

    这样的事情怎么样:

    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)
    

    说明:我们使用distOneTwoThree 和所有Scatter 点之间计算所有成对欧几里得距离。然后,我们根据与One (k = 1)、Two (k = 2)、Three (k = 3) 的最小距离为每个 Scatter 点分配一个标签 k

    请注意,(9.6, 3.1) 处的Scatter 点确实被正确“分类”为属于Two (k = 2);您可以通过在ggplot 情节链中添加coord_fixed() 来确认这一点。

    【讨论】:

    • 非常有帮助,尽管我不确定如何(或在何处)修改您的代码以获得具有所需结果的新数据框,尽管绘制的内容看起来很完美。
    • @B.Davis 这应该很简单。 Data 是你原来的data.frame。我所做的只是将Data 和集群信息从dist 绑定到一个新的data.frame,然后将其传递给ggplot
    • @B.Davis PS。我在代码中添加了一些 cmets,希望能有所帮助。
    猜你喜欢
    • 2015-03-05
    • 1970-01-01
    • 1970-01-01
    • 2014-09-19
    • 2016-11-15
    • 2017-11-07
    • 1970-01-01
    • 1970-01-01
    • 2021-10-24
    相关资源
    最近更新 更多