【问题标题】:Binning with data.tables使用 data.tables 进行分箱
【发布时间】:2016-10-05 22:49:55
【问题描述】:

我想使用一个表创建 bin 并将它们应用到另一个表。我这样做了:

library(data.table)
library(Hmisc) # for cut2

# (1) Make two data.tables A and B
a <- sample(10:100, 10000, replace=TRUE)
b <- sample(10:90, 10000, replace=TRUE)
A <- data.table(a,b)
a <- sample(0:110, 10000, replace=TRUE)
b <- sample(50:100, 10000, replace=TRUE)
B <- data.table(a,b)

# (2) Create bins using table A (per column)
cc<-A[,lapply(.SD,cut2,g=5, onlycuts=TRUE)]

# (3) Add -Inf and Inf to the cuts (to cope with values in B outside the bins of A)
cc<-rbind(data.table(a=-Inf,b=-Inf),cc,data.table(a=Inf,b=Inf))

# (4) Apply the bins to table B (and table A for inspection)
A[,ac:=as.numeric(cut2(A$a,cuts=cc$a))]
A[,bc:=as.numeric(cut2(A$b,cuts=cc$b))]
B[,ac:=as.numeric(cut2(B$a,cuts=cc$a))]
B[,bc:=as.numeric(cut2(B$b,cuts=cc$b))]

它有效,但我想以正确的方式进行第 4 步,即类似于第 2 步。

我最接近的是:

B[,lapply(.SD,cut2,cuts=cc$a),.SDcols=c("a","b")]

但这不是我想要的,因为它只对所有列使用一列 (a) 的 bin,并且它给出了间隔而不是 bin 编号,因为我无法弄清楚如何放置 as.numeric。

提前感谢大家的指点

更新 感谢 math.coffee 的有用建议。我现在有一个通用的方法:

# (3) Add -Inf and Inf to the cuts (to cope with values in B outside the bins of A)
C<-data.table(c(-Inf,Inf),c(-Inf,Inf))
setnames(C,colnames(cc))
qc<-rbind(C[1],qc,C[2])

# (4) Apply the bins to table B 
B[,paste0(colnames(cc),"q"):=mapply(function(x, cuts) as.numeric(cut2(x, cuts)), .SD, qc, SIMPLIFY=F),.SDcols=colnames(qc)]

【问题讨论】:

    标签: r data.table binning


    【解决方案1】:

    您可以使用mapply.SD 中的列与cc 中的列匹配。

    B[, mapply(cut2, .SD, cc),.SDcols=c("a","b")]
    # or if you wish to assign the result
    B[, c('ac', 'bc'):=mapply(cut2, .SD, cc, SIMPLIFY=F),.SDcols=c("a","b")]
    

    这将以"[47, 65)"的间隔形式返回结果;如果你想要数字形式,那么只需使用

    mapply(function(x, cuts) as.numeric(cut2(x, cuts)), .SD, cc)
    

    注意mapply 实际上不会匹配.SDcols 的名称与cc 的名称;它只是按照它们出现的顺序使用列。如果您想确保它们匹配,可以使用.SDcols=names(cc)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-29
      • 2018-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多