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

前端 未结 3 1824
隐瞒了意图╮
隐瞒了意图╮ 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:30

    We could also use the between function from the data.table package.

    # Create a data frame
    dat <- data.frame(Users = 1:7, Age = c(2, 7, 10, 3, 8, 12, 15))
    
    # Convert the data frame to data table by reference
    # (data.table is also a data.frame)
    setDT(dat)
    
    # Define a list with the cut pairs
    cuts <- list(c(0, 5), c(6, 10), c(11, 15))
    
    # Cycle through dat and cut it into list of data tables by the values in Age
    # matching the defined cuts
    lapply(X = cuts, function(i) {
      dat[between(x = dat[ , Age], lower = i[1], upper = i[2])]
    })
    

    Output:

    [[1]]
       Users Age
    1:     1   2
    2:     4   3
    
    [[2]]
       Users Age
    1:     2   7
    2:     3  10
    3:     5   8
    
    [[3]]
       Users Age
    1:     6  12
    2:     7  15
    

    Many other things are possible, including doing it by group, data.table is rather flexible.

提交回复
热议问题