Home > front end >  How to divide the range up into groups in R?
How to divide the range up into groups in R?

Time:10-07

Data collected for a study of the cost of meals at 50 restaurants located in a major city and 50 restaurants located in that city’s suburbs.

city <- c(21,23,23,27,28,29,32,32,33,34,
          35,38,39,40,40,40,41,42,42,43,
          43,43,44,44,44,45,45,46,48,48,
          )

suburb <- c(22,26,28,29,29,30,31,32,33,33,
            34,34,35,36,37,37,37,37,37,38,
            38,39,40,40,41,41,42,42,43,43
            )

I would like to catogorize the data like this:

First group  :(20~30) 21 24 25 29
Second group :(30~40) 32 35 36 39
   .                   .
   .                   .

Is there any functions I can use? Thanks.

CodePudding user response:

Use cut split:

split(city, cut(city, breaks = seq(20, 50, 10)))

$`(20,30]`
[1] 21 23 23 27 28 29

$`(30,40]`
 [1] 32 32 33 34 35 38 39 40 40 40

$`(40,50]`
 [1] 41 42 42 43 43 43 44 44 44 45 45 46 48 48

Try with stack as well to get a dataframe-like result:

stack(split(city, cut(city, breaks = seq(20, 50, 10))))
  •  Tags:  
  • r
  • Related