Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cut() - include lowest values

Tags:

r

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?

like image 819
paulburg Avatar asked Sep 03 '12 09:09

paulburg


2 Answers

x <- -10:10

cut(x, c(-Inf, -2, 4, 6, 7, +Inf))

# Levels: (-Inf,-2] (-2,4] (4,6] (6,7] (7, Inf]
like image 170
Sven Hohenstein Avatar answered Oct 08 '22 23:10

Sven Hohenstein


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
like image 20
Backlin Avatar answered Oct 09 '22 00:10

Backlin