gpt4 book ai didi

r - 如何根据R中的接近度将数字排序到列表中

转载 作者:行者123 更新时间:2023-12-04 23:25:30 25 4
gpt4 key购买 nike

假设我有一个向量中的数字列表。我正在尝试提出一个脚本,该脚本将列表划分或排序为(不一定是偶数)集合,这些集合的数字相对于向量中的其他数字彼此非常接近。您可以假设向量中的数字按升序排列。

my_list<- c(795, 798, 1190, 1191, 2587, 2693, 2796, 3483, 3668)

也就是说,我需要帮助想出一个脚本来将这些数字划分并分配到集合中
set_1<- c(795, 798) # these 2 numbers are fairly close to each other
set_2<- c(1190, 1191) # these numbers would be another set
set_3<- c(2587, 2693, 2796) # these numbers would be another set relative to the other numbers
set_4<- c(3483, 3668) # the last set

非常感谢任何帮助或建议。

最佳答案

一般来说,你所要求的叫做Cluster Analysis ,对此有许多可能的方法和算法,其中许多已经在此处列出的 R 包中可用:http://cran.r-project.org/web/views/Cluster.html .

以下是如何使用层次聚类对数据进行聚类的示例。

tree <- hclust(dist(my_list))
groups <- cutree(tree, h = 300)
# [1] 1 1 2 2 3 3 3 4 4
split(my_list, groups)
# $`1`
# [1] 795 798
#
# $`2`
# [1] 1190 1191
#
# $`3`
# [1] 2587 2693 2796
#
# $`4`
# [1] 3483 3668

关于r - 如何根据R中的接近度将数字排序到列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13547190/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com