Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to divide the range up into groups in R?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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))))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading