Ladislav Naďo
Ladislav Naďo

Reputation: 862

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

I need to sort my vector values into custom intervals and subsequently identify which element belong to which interval.

For example if a vector is:

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

and the intervals are:

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

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

...how do I combine x and interval.vector to get this:

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

Upvotes: 2

Views: 905

Answers (1)

Roman Luštrik
Roman Luštrik

Reputation: 70623

You can also use 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

Another option is the very efficient findInterval function, but I'm not sure how robust this solution on different variations of x

findInterval(x, interval.vector + 1L, all.inside = TRUE)
## [1] 1 1 2 2 3 4

Upvotes: 6

Related Questions