kentkr
kentkr

Reputation: 168

How to bin columns based on the minimum and maximum of a column

I've got a dataset that when I score needs to be converted from a continuous scale to categorical. Each value will be put into one of those categories at 10 intervals based on the minimum and maximum of that column. So if the minimum = 1 and the maximum = 100 there will be 10 categories so that any value from 1-10 = 1, and 11-20 = 2, 21-30 = 3, ..., 91-100 = 10. Here's what my data looks like

df <- as.data.frame(cbind(test1 = sample(13:52, 15),
                          test2 = sample(16:131, 15)))
> df
   test1 test2
1     44   131
2     26    83
3     74    41
4      6    73
5     83    20
6     63   110
7     23    29
8     42    64
9     41    40
10    10    96
11     2    39
12    14    24
13    67    30
14    51    59
15    66    37

So far I have a function:

trail.bin <- function(data, col, min, max) {
  for(i in 1:10) {
    for(e in 0:9) {
      x <- as.data.table(data)
      mult <- (max - min)/10
      x[col >= min+(e*mult) & col < min+(i*mult), 
        col := i]
    }
  }
  return(x)
}

What I'm trying to do is take the minimum and maximum, find what the spacing of intervals would be (mult), then use two loops on a data.table reference syntax. The outcome I'm hoping for is:

df2
   test1 test2
1      5   131
2      3    83
3      8    41
4      1    73
5      9    20
6      7   110
7      3    29
8      5    64
9      5    40
10     2    96
11     1    39
12     2    24
13     7    30
14     6    59
15     7    37

Thanks!

Upvotes: 0

Views: 725

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388982

You could create a function using cut

library(data.table)

trail.bin <- function(data, col, n) {
  data[, (col) := lapply(.SD, cut, n, labels = FALSE), .SDcols = col]
  return(data)
}

setDT(df)
trail.bin(df, 'test1', 10)

You can also pass multiple columns

trail.bin(df, c('test1', 'test2'), 10)

Upvotes: 1

Related Questions