0

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.

codingxxx
  • 37
  • 4
  • Does this answer your question? [R divide data into groups](https://stackoverflow.com/questions/30356275/r-divide-data-into-groups) – Harrison Jones Oct 06 '22 at 15:34

1 Answers1

1

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))))
Maël
  • 45,206
  • 3
  • 29
  • 67
  • Thanks. I used `stack(split(city, cut(city, breaks = seq(20, 50, 10))))` which works very well. But I would like to know how to count the frequency of each group. Thanks – codingxxx Oct 06 '22 at 16:03
  • You can ask another question for that. – Maël Oct 06 '22 at 18:09