为所有列data.table按组选择最后一行 [英] Select last row by group for all columns data.table

查看:66
本文介绍了为所有列data.table按组选择最后一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很惊讶地执行以下操作:

I was surprised doing the following:

R) system.time(lastOrder <- order[,lapply(.SD,tail,1),by="TRADER_ID,EXEC_IDATE"]);
utilisateur     système      écoulé 
       1.45        0.00        1.53 
R) nrow(order)
[1] 75301
R) ncol(order)
[1] 23

以为很长,后来我做到了

Thought it was very long, then I did

R) system.time(lastOrder <- order[,list(test=tail(EXEC_IDATE,1)),by="TRADER_ID,EXEC_IDATE"]);
utilisateur     système      écoulé 
       0.14        0.00        0.14 

据我了解,如果您知道所有要选择的行都已完成,并且大部分工作已经完成,所以我不明白为什么将其应用于所有列的时间应该长10倍。我在第一行代码上做错什么了吗,这是我知道按组选择最后一行的唯一方法

as far as I understand, if you know all the rows to select and work on most of the work is done, then I don't see why apply this to all columns should be 10x longer. Am I doing something wrong on the first bit of code, this is the only way I know to select last rows by group

推荐答案

按组的最后一行:

DT[, .SD[.N], by="TRADER_ID,EXEC_IDATE"]            # (1)

,或者更快(避免使用 .SD 可能的话,以提高速度):

or, faster (avoid use of .SD where possible, for speed) :

w = DT[, .I[.N], by="TRADER_ID,EXEC_IDATE"][[3]]    # (2)
DT[w]

注意以下功能请求将使方法(1)和方法(2)一样快:

Note that the following feature request will make approach (1) as fast as approach (2) :

FR#2330优化.SD [i]查询以保持美观,但使其速度保持不变

这篇关于为所有列data.table按组选择最后一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆