如何获得一个向量,该向量标识元素属于 R 中的哪些区间

How to get a vector which identify to which intervals the elements belong in R

我需要将我的矢量值排序到自定义区间,然后 确定哪个元素属于哪个区间

例如,如果向量是:

x <- c(1,4,12,13,18,24)

间隔为:

interval.vector <- c(1,7,13,19,25)

1st interval:    1 - 7
2nd interval:    7 - 13
3rd interval:   13 - 19
4th interval:   19 - 25

...我如何结合 xinterval.vector 得到这个:

element:   1   4   12   13   18   24
interval:  1   1    2    2    3    4

您也可以使用cut

x <- c(1,4,12,13,18,24)
interval.vector <- c(1,7,13,19,25)
x.cut <- cut(x, breaks = interval.vector, include.lowest = TRUE)

data.frame(x, x.cut, group = as.numeric(x.cut))

   x   x.cut group
1  1   [1,7]     1
2  4   [1,7]     1
3 12  (7,13]     2
4 13  (7,13]     2
5 18 (13,19]     3
6 24 (19,25]     4

另一个选项是非常有效的 findInterval 函数,但我不确定这个解决方案在 x

的不同变体上有多稳健
findInterval(x, interval.vector + 1L, all.inside = TRUE)
## [1] 1 1 2 2 3 4