R 如何基于列的最小值和最大值对列进行装箱

R 如何基于列的最小值和最大值对列进行装箱,r,function,dataframe,data.table,bin,R,Function,Dataframe,Data.table,Bin,我有一个数据集,当我得分时,需要将其从连续量表转换为分类量表。根据该列的最小值和最大值,每10个间隔将每个值放入其中一个类别。因此,如果最小值=1,最大值=100,那么将有10个类别,因此1-10=1,11-20=2,21-30=3,…,91-100=10的任何值。下面是我的数据 df <- as.data.frame(cbind(test1 = sample(13:52, 15), test2 = sample(16:131, 15))

我有一个数据集,当我得分时,需要将其从连续量表转换为分类量表。根据该列的最小值和最大值,每10个间隔将每个值放入其中一个类别。因此,如果最小值=1,最大值=100,那么将有10个类别,因此1-10=1,11-20=2,21-30=3,…,91-100=10的任何值。下面是我的数据

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

谢谢

您可以使用cut创建函数


列中的最大值不应该是10吗?cutdf$test1,break=10,labels=FALSE工作吗?我被吓坏了。非常感谢你!
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)
}
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
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)
trail.bin(df, c('test1', 'test2'), 10)