R – How to split a continuous variable into intervals of equal length (defined number) and list the interval with cut points only in R

intervalsr

I would like to divide a set of data into four equal size interval, e.g.:

x=c(0:10)

G1: [0,2.5)

G2: [2.5,5)

G3: [5,7.5)

G4: [7.5,10]

Is there anyway I can split the data into intervals of equal length (say four in this case) and get the below list including the min and max values:

0   2.5   5   7.5   10 

Thanks!

Best Answer

You're looking for cut

cut(1:10, c(1, seq(2.5, 10, by=2.5)), include.lowest = T)
#  [1] [1,2.5]  [1,2.5]  (2.5,5]  (2.5,5]  (2.5,5]  (5,7.5]  (5,7.5]  (7.5,10]
#  [9] (7.5,10] (7.5,10]
# Levels: [1,2.5] (2.5,5] (5,7.5] (7.5,10]

If you just want the evenly spaced breaks, use seq

x <- 0:10
seq(min(x), max(x), len=5)
# [1]  0.0  2.5  5.0  7.5 10.0
Related Topic