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

use*_*954 4 sorting r vector

假设我在向量中有一个数字列表.我试图想出一个脚本,将列表分成或排序成(不一定是偶数)集合,这些集合的数量相对于向量中的其他数字彼此非常接近.你可以假设向量中的数字是按升序排列的.

my_list<- c(795, 798, 1190, 1191, 2587, 2693, 2796, 3483, 3668)
Run Code Online (Sandbox Code Playgroud)

也就是说,我需要帮助提出一个脚本,它将这些数字分成几组并分配到哪里

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
Run Code Online (Sandbox Code Playgroud)

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

flo*_*del 5

一般来说,你要求的是簇分析,其中有许多可能的方法和算法,其中许多已经在这里列出的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
Run Code Online (Sandbox Code Playgroud)