unique.data.table 选择最后一行代替第一行 [英] unique.data.table select last row in place of the first

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

问题描述

在键控 data.table 上调用 unique 您将在每个组中拥有唯一的行.如果有重复的行,将采用第一行.当我需要最后一个而不是(通常是最后一个临时事务)时,我使用 .SD[.N]

calling unique on a keyed data.table you'll have unique lines per each group. In case of duplicated lines the first will be taken. When I need the take the last instead ( in general the last temporal transaction) I use .SD[.N]

library(data.table)
library(microbenchmark)

dt <- data.table(id=sample(letters, 10000, T), var=rnorm(10000), key="id")

microbenchmark(unique(dt), dt[, .SD[.N], by=id])
Unit: microseconds
                   expr      min        lq    median       uq        max neval
             unique(dt)  570.882  586.1155  595.8975  608.406   3209.122   100
 dt[, .SD[.N], by = id] 6532.739 6637.7745 6694.3820 6776.968 208264.433   100

你知道更快的方法吗?

推荐答案

创建一个 data.table,其中包含关键变量的唯一组合,然后使用 mult = 'last'

Create a data.table that contains the unique combinations of the key variables then join using mult = 'last'

使用 .SD 很方便,但速度较慢.如果您愿意,可以改用 .I.

Using .SD is convenient, but slow. You could use .I instead if you wished.

dtu <- unique(dt)[,key(dt), with = FALSE]
dt[dtu, mult = 'last']

或者

 dt[ dt[,  .I[.N], by = key(dt)]$V1]

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

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