说我有向量 x
x <- c(1, 1, 1.1, 2, 1, 2.1, 2.6)
tol <- 0.4
Run Code Online (Sandbox Code Playgroud)
我如何获得容差范围 ( tol)内“唯一”元素组的索引,如下表所示。我事先不知道有多少这样的团体。
[[1]]
[1] 1 2 3 5
[[2]]
[1] 4 6
[[3]]
[1] 7
Run Code Online (Sandbox Code Playgroud)
谢谢
也许这是一把杀死蚊子的锤子,但我想到了单变量密度聚类:该dbscan库使您能够做到这一点:
library(dbscan)
groups <- dbscan(as.matrix(x), eps=tol, minPts=1)$cluster
#### [1] 1 1 1 2 1 2 3
Run Code Online (Sandbox Code Playgroud)
您不需要提前知道组的数量。
它在输出中为您提供簇编号,但如果您愿意,您可以采用组平均值并将它们四舍五入到最接近的整数。获得此信息后,您可以生成如下所示的列表:
split(seq_along(x), groups)
#### $`1`
#### [1] 1 2 3 5
#### ...
Run Code Online (Sandbox Code Playgroud)
编辑:重叠行为: 该算法将同一组归因于彼此容差范围内的所有元素(按邻近度工作)。因此,如果存在重叠,您最终得到的组数可能会少于预期。