2016-10-05 2 views
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)] 

答えて

0

あなたはccのものに.SDの列を一致させるためにmapplyを使用することができます。私は今、一般的なアプローチを持っています。

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は、実際にccの名前で.SDcolsの名前を一致しません。表示される順序で列を使用するだけです。一致するようにしたい場合は、.SDcols=names(cc)を使用できます。

関連する問題