Search code examples
rintervalsbin

R - Cut numeric vector into bins using closed and open intervals


Using the cut() function I know how to take a numeric vector and bin it according to semi-open intervals

(0, 10], (10. 19], (19, 20], (20, 26], etc...

or

[0, 10), [10, 19), [19, 20), [20, 26), etc....

How can I bin a vector with a combination of closed and open intervals, such as

(0, 10), [10, 20], (20, 29], (29, 48), [48], (48, 56), etc...?

Please note that I want to create a closed interval that consists of a single number.

Is there a way to use the cut() function or some other function to do this? Is it time for a new function?!

EDIT

boyScale <- function(x) {
ret <- 
ifelse(x < 16.3,  1,
ifelse(x = 16.3,  2,
ifelse(x < 20.8,  3,
ifelse(x = 20.8,  4,
ifelse(x < 21.91, 5,
ifelse(x = 21.91, 6,
ifelse(x < 28.2,  7,
ifelse(x = 28.2,  8,
ifelse(x < 37.3,  9,
ifelse(x = 37.3, 10, 11))))))))))
return(ret)
}

I tried this with the number 25.24, and got the following error message

Error in ifelse(x = 16.3, 2, ifelse(x < 20.8, 3, ifelse(x = 20.8, 4, ifelse(x < : unused argument (x = 16.3) 

Any ideas?


Solution

  • If your input data and desired no. of bins both aren't too large, you can use nested ifelses.

    y <- ifelse(x < 10, 1,
         ifelse(x <= 20, 2,
         ifelse(x < 30, 3,
         ifelse(x < 48, 4,
         ifelse(x <= 48, 5, .....)))))
    

    Is there any structure in the data that you can exploit?