R divide data into groups

前端 未结 1 821
孤街浪徒
孤街浪徒 2021-01-12 11:13

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 va

相关标签:
1条回答
  • 2021-01-12 12:06

    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
    
    0 讨论(0)
提交回复
热议问题