I want to cut my data using defined breaks in cut()
:
x = c(-10:10)
cut(x, c(-2,4,6,7))
[1] <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> (-2,4] (-2,4] (-2,4] (-2,4] (-2,4] (-2,4] (4,6] (4,6] (6,7] <NA> <NA>
[21] <NA>
Levels: (-2,4] (4,6] (6,7]
However, I also want to obtain the levels (minimum:-2]
and (7:maximum]
. In the function recode()
of the car-package one can use "lo:". Is there a similar thing available for cut?
x <- -10:10
cut(x, c(-Inf, -2, 4, 6, 7, +Inf))
# Levels: (-Inf,-2] (-2,4] (4,6] (6,7] (7, Inf]
findInterval
is the answer.
i <- findInterval(x, c(-2,4,6,7))
cbind(x, i)
x i
[1,] -10 0
[2,] -9 0
[3,] -8 0
[4,] -7 0
[5,] -6 0
[6,] -5 0
[7,] -4 0
[8,] -3 0
[9,] -2 1
[10,] -1 1
[11,] 0 1
[12,] 1 1
[13,] 2 1
[14,] 3 1
[15,] 4 2
[16,] 5 2
[17,] 6 3
[18,] 7 4
[19,] 8 4
[20,] 9 4
[21,] 10 4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With