How do I split a data frame based on range of column values in R?

前端 未结 3 1809
隐瞒了意图╮
隐瞒了意图╮ 2021-01-12 22:28

I have a data set like this:

Users   Age
1        2
2        7
3        10
4        3
5        8
6        20

How do I split this data set i

3条回答
  •  太阳男子
    2021-01-12 22:38

    You can combine split with cut to do this in a single line of code, avoiding the need to subset with a bunch of different expressions for different data ranges:

    split(dat, cut(dat$Age, c(0, 5, 10, 15), include.lowest=TRUE))
    # $`[0,5]`
    #   Users Age
    # 1     1   2
    # 4     4   3
    # 
    # $`(5,10]`
    #   Users Age
    # 2     2   7
    # 3     3  10
    # 5     5   8
    # 
    # $`(10,15]`
    # [1] Users Age  
    # <0 rows> (or 0-length row.names)
    

    cut splits up data based on the specified break points, and split splits up a data frame based on the provided categories. If you stored the result of this computation into a list called l, you could access the smaller data frames with l[[1]], l[[2]], and l[[3]] or the more verbose:

    l$`[0,5]`
    l$`(5,10]`
    l$`(10, 15]`
    

提交回复
热议问题