R 在data.table中按组计数快速排在前N位

R 在data.table中按组计数快速排在前N位,r,count,data.table,greatest-n-per-group,R,Count,Data.table,Greatest N Per Group,我想知道根据分组的出现次数来划分分组的首选方法 dcast( df[,.(.N), by = .(cust_segment, cust_postal) ][,.(cust_postal, postal_rank = frankv(x=N, order=-1, ties.method = 'first') ), keyby=cust_segment ][postal_rank<=3], cust_segment ~ past

我想知道根据分组的出现次数来划分分组的首选方法

dcast(
  df[,.(.N),
     by = .(cust_segment, cust_postal)
     ][,.(cust_postal,
          postal_rank = frankv(x=N, order=-1, ties.method = 'first')
     ), keyby=cust_segment
     ][postal_rank<=3],
  cust_segment ~ paste0('postcode_rank_',postal_rank), value.var = 'cust_postal' 
)
# desired output:
# cust_segment postcode_rank_1 postcode_rank_2 postcode_rank_3
#            A           51274           64588           59212
#            B           63590           69477           50380
#            C           60619           66249           53494 ...etc...
例如,我有属于细分市场且拥有邮政编码的客户。我想知道每个部分最常见的3个邮政编码

library(data.table)
set.seed(123)
n <- 1e6
df <- data.table( cust_id = 1:n,
                  cust_segment = sample(LETTERS, size=n, replace=T),
                  cust_postal = sample(as.character(5e4:7e4),size=n, replace=T)
                 )

这是最好的方法,还是单一的方法?

从评论中找出弗兰克的答案:

使用
forder
代替
frankv
并使用
keyby
,因为这比仅使用
by

df[, .N, 
   keyby = .(cust_segment, cust_postal)
   ][order(-N), r := rowid(cust_segment)
     ][r <= 3, dcast(.SD, cust_segment ~ r, value.var ="cust_postal")]

    cust_segment     1     2     3
 1:            A 51274 53440 55754
 2:            B 63590 69477 50380
 3:            C 60619 66249 52122
 4:            D 68107 50824 59305
 5:            E 51832 65249 52366
 6:            F 51401 55410 65046
df[,.N,
keyby=(客户段,客户邮政)
][订单(-N),r:=行ID(客户段)

][r看起来不错,不过我想你应该
:=
frankv而不是制作一个新表。用一个调用
forder
而不是多个调用
frankv
也可能更快:
df[,.N,keyby=(cust_段,cust_posal)][order(-N),r:=rowid(cust_段)][r@Frank是的,谢谢,你的速度快了25%
library(microbenchmark)

microbenchmark(C8H10N4O2 = dcast(
                                df[,.(.N),
                                   by = .(cust_segment, cust_postal)
                                   ][,.(cust_postal,
                                        postal_rank = frankv(x=N, order=-1, ties.method = 'first')
                                   ), keyby=cust_segment
                                   ][postal_rank<=3],
                                cust_segment ~ paste0('postcode_rank_',postal_rank), value.var = 'cust_postal' 
                              ),
              frank = df[, .N, 
                         keyby = .(cust_segment, cust_postal)
                         ][order(-N), r := rowid(cust_segment)
                           ][r <= 3, dcast(.SD, cust_segment ~ r, value.var ="cust_postal")])
Unit: milliseconds
     expr      min       lq     mean   median       uq      max neval
C8H10N4O2 136.3318 140.8096 156.2095 145.6099 170.4862 205.8457   100
    frank 102.2789 110.0140 118.2148 112.6940 119.2105 192.2464   100