【发布时间】: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