2016-10-05 53 views
0

我想使用一個表創建箱並將它們應用到另一個表。我這樣做:Binning with 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))] 

它的工作原理,但我想打第4步以適當的方式,即類似於步驟2

我來最接近的是這樣的:

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

但是這不是我想要的,因爲它對所有列使用只有一列(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

您可以使用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實際上不會與cc名稱匹配的.SDcols名稱;它只是按照它們出現的順序使用這些列。如果你想確保它們匹配,你可以使用.SDcols=names(cc)