data.table选择每个组的第一行限制为n-1列? [英] data.table select first row of each group limited to n-1 columns?

查看:59
本文介绍了data.table选择每个组的第一行限制为n-1列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

。SD功能的data.table帮助显示了如何选择每个组的第一行:

The data.table help for the ".SD" function shows how to select the first row of each group:

DT = data.table(x=rep(c("b","a","c"),each=3), v=c(1,1,1,2,2,1,1,2,2), y=c(1,3,6), a=1:9, b=9:1)
DT

DT[, .N, by=x]                         # number of rows in each group

这对我来说最有效,但是当我使用所有列时会中断来定义组,我不知道为什么,所以我想知道这是否是一个错误。示例:

This mostly works well for me, but it breaks when I use all columns to define the group and I don't see why, so I wonder if it's a bug. Example:

# Selecting by n-1 columns works:
DT[, .SD[1], by=c("x", "y", "v", "a")]
   x y v a b
1: b 1 1 1 9
2: b 3 1 2 8
3: b 6 1 3 7
4: a 1 2 4 6
5: a 3 2 5 5
6: a 6 1 6 4
7: c 1 1 7 3
8: c 3 2 8 2
9: c 6 2 9 1

# The result of selecting by all columns is not what I expected:
DT[, .SD[1], by=c("x", "y", "v", "a", "b")]
Empty data.table (0 rows) of 5 cols: x,y,v,a,b


推荐答案

如@评论所示christoph, .SD 不包含组列(我认为这是出于效率目的,以便不存储重复的组值),您可以通过以下操作进行验证:

As commented by @christoph, .SD doesn't include group columns (which I believe is for efficiency purpose so as not to store duplicated group values), you can verify it by doing this:

unique(DT[, .(name = names(.SD)), by=c('x','v')]$name)
# [1] "y" "a" "b"

unique(DT[, .(name = names(.SD)), by=c('x','v','a')]$name)
# [1] "y" "b"

因此,如果按所有列分组,则 .SD 里面什么也没有;对于您的特定情况,您可以只使用 unique 并将 group 变量传递给 by 参数,该参数将根据 by 列删除重复项:

So if you group by all columns, .SD has nothing in it; And for your specific case, you can just use unique and pass the group variables to the by parameter, which will drop duplicates based on the by columns:

unique(DT, by=c('x','v'))

#   x v y a b
#1: b 1 1 1 9
#2: a 2 1 4 6
#3: a 1 6 6 4
#4: c 1 1 7 3
#5: c 2 3 8 2

unique(DT, by=c('x','v','y','a','b'))

#   x v y a b
#1: b 1 1 1 9
#2: b 1 3 2 8
#3: b 1 6 3 7
#4: a 2 1 4 6
#5: a 2 3 5 5
#6: a 1 6 6 4
#7: c 1 1 7 3
#8: c 2 3 8 2
#9: c 2 6 9 1

这篇关于data.table选择每个组的第一行限制为n-1列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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