Search code examples
rhistogrambinning

Symmetric binning around 0


Suppose I have a vector:

vec.test <- c(-1.2, -1, -0.9, -0.5, 0, 0.5, 0.9 , 1, 1.2)

I'd like to bin it into following bins: (-2, -1], (-1, 1), [1, 2)

Is there a more elegant/automatic way of doing this than the following?

cut(vec.test, c(-2, -1+.Machine$double.eps, 1-.Machine$double.eps, 2), right=TRUE)

Solution

  • If you don't care about the labels, you could do something like this:

    vec.test <- seq(-2, 2, by=0.5)
    names(vec.test) <- cut(abs(vec.test), c(-1, 1, 2), right=FALSE, labels=FALSE) * 
                         (-1)^(vec.test <= -1 ) 
    #<NA>   -2   -2    1    1    1    2    2 <NA> 
    #-2.0 -1.5 -1.0 -0.5  0.0  0.5  1.0  1.5  2.0