0
1つのテーブルを使用してビンを作成し、別のテーブルに適用したいとします。私はこれをした:data.tablesでのビニング
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))]
それは動作しますが、私は私が来た最も近いが、これだっ2.
段階に、適切な方法でステップ4を作りたいと類似すなわち:
B[,lapply(.SD,cut2,cuts=cc$a),.SDcols=c("a","b")]
しかし、これは私が望むものではありません。すべての列に対して1つの列(a)だけのビンを使用し、as.numericの配置方法を理解することができないので、ビン番号よりもむしろ間隔を与えます。ありがとう
UPDATE任意のポインタを事前に
感謝のは、有益な助言のためmathematical.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)]