I have a data frame and I want to split one column values into n
groups. So, I have a column data$dist
with approximately 10k records, where max value is 23180 and min value 8951. And I want to split the values into 10 groups of equal range, i.e (23180-8951)/10 = 1423. Which means that all values between 8951 and 10374 go into 1 group. And so on. How can I do it?
Asked
Active
Viewed 1.1k times
7

Bob
- 10,427
- 24
- 63
- 71
-
See `?cut`, use it with `seq`. `quantile` would be used instead of `seq` if you wanted equal numbers of observations per group, rather than equal ranges per group. – Gregor Thomas May 20 '15 at 17:45
1 Answers
11
You can use cut
and split
, as in the toy example below:
set.seed(2015)
d <- data.frame(i=1:20,z=runif(20))
# i z
# 1 1 0.06111892
# 2 2 0.83915986
# 3 3 0.29861322
# 4 4 0.03143242
# 5 5 0.13857171
# 6 6 0.35318471
# 7 7 0.49995552
# 8 8 0.07707116
# 9 9 0.65134483
# 10 10 0.51172371
# 11 11 0.70285557
# 12 12 0.39172125
# 13 13 0.03306277
# 14 14 0.40940319
# 15 15 0.74234713
# 16 16 0.88301877
# 17 17 0.26623321
# 18 18 0.07427093
# 19 19 0.81368426
# 20 20 0.38194719
split(d,cut(d$i,seq(0,20,length.out=5)))
# $`(0,5]`
# i z
# 1 1 0.06111892
# 2 2 0.83915986
# 3 3 0.29861322
# 4 4 0.03143242
# 5 5 0.13857171
#
# $`(5,10]`
# i z
# 6 6 0.35318471
# 7 7 0.49995552
# 8 8 0.07707116
# 9 9 0.65134483
# 10 10 0.51172371
#
# $`(10,15]`
# i z
# 11 11 0.70285557
# 12 12 0.39172125
# 13 13 0.03306277
# 14 14 0.40940319
# 15 15 0.74234713
#
# $`(15,20]`
# i z
# 16 16 0.88301877
# 17 17 0.26623321
# 18 18 0.07427093
# 19 19 0.81368426
# 20 20 0.38194719

Marat Talipov
- 13,064
- 5
- 34
- 53