Create intervals with equal spacing around 0

advertisements

I am making breaks based on input values in R, and then applying equal intervals based on those values.

To do this I supply an input vector:

for_break = c(-100, -90, -80, -50, 0, 3, 5, 20, 30, 40, 80)

then I apply equal interval breaks, with 5 intervals total using:

library(classInt)

breaks = classIntervals(for_break, n = 5, style = "equal", intervalClosure = "right")

I return the breaks with:

breaks_num = breaks$brks

which returns:

[1] -100  -64  -28    8   44   80

I want to have a break centered around the number 0 though.

Is there a way to supply an input vector and provide equal interval spacing around zero on both the positive and negative side?

As an example if I supplied this input vector:

c(-8, -6, -3, -2, 2, 4, 6, 9)

and specified that I wanted equal spacing on the positive and negative side of zero, with 3 intervals on each side I would get:

c(-8.000, -5.333, -2.666, 0.000, 3.000, 6.000, 9.000)


What about:

for_break = c(-100, -90, -80, -50, 0, 3, 5, 20, 30, 40, 80)

equalSpacing <- function( vector, per.side ) {
  negs <- seq.int( from = min( vector ), to = 0, length.out = per.side + 1L )
  pos <- seq.int( from = 0, to = max( vector ), length.out = per.side + 1L )
  return( c( negs, pos[ pos != 0 ] ) )
}

equalSpacing( for_break, 4 )