Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
518 views
in Technique[技术] by (71.8m points)

split - R divide data into groups

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...