-2

An example

mtcars$qsec
 [1] 16.46 17.02 18.61 19.44 17.02 20.22 15.84 20.00 22.90 18.30 18.90 17.40
[13] 17.60 18.00 17.98 17.82 17.42 19.47 18.52 19.90 20.01 16.87 17.30 15.41
[25] 17.05 18.90 16.70 16.90 14.50 15.50 14.60 18.60

I want to stratify or group that variable. The point is I want to do it in the same steps (e.g. 5).

Currently I would do it like that

mtcars$qsec_group[mtcars$qsec < 10] <- '10 or less'
mtcars$qsec_group[mtcars$qsec >= 10 & mtcars$qsec < 15] <- '10-15'
mtcars$qsec_group[mtcars$qsec >= 15 & mtcars$qsec < 20] <- '15-20'

It is quite unflexible. Is there an R-way to say Stratify that variable in steps of 5.?

buhtz
  • 10,774
  • 18
  • 76
  • 149
  • You can use `cut` to do this – akrun Nov 24 '16 at 12:25
  • 3
    Possible duplicate of [How do I split a data frame based on range of column values in R?](http://stackoverflow.com/questions/24707936/how-do-i-split-a-data-frame-based-on-range-of-column-values-in-r) Or [Group numeric values by the intervals](http://stackoverflow.com/questions/13559076/group-numeric-values-by-the-intervals) – Ronak Shah Nov 24 '16 at 12:26

1 Answers1

0

We can use cut

with(mtcars, cut(q_sec, breaks = c(10, 15, 20), labels = c('10 or less', '10-15', '15-20'))
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Where are the "steps of 5"? That was the point of my question and the difference to the possible duplicates. – buhtz Nov 24 '16 at 12:48
  • 1
    @buhtz You can change the `breaks` to `breaks = seq(10, 30, by = 5)` or so – akrun Nov 24 '16 at 12:49