我正在使用一个大 data.table 并使用“by”来“分组”3 个变量。
我的数据表是 d
并有键“ma”(10 位整数,但我在下面缩短了它)。
但设置by="ma,year,month"
(这对我来说是更直观的 group by 语句)没有给出我想要的。例如,ma = 284 有 3 个 2011 年 11 月的条目,或 ma= 672 有 2 个 2011 年 12 月的条目。
> d[,list(n=length(trx_num)),by=list(ma,year,month)]
ma year month n
1: 284 2011 12 3
2: 284 2012 1 1
3: 284 2011 11 5
4: 284 2011 11 1
5: 284 2011 11 2
---
5782971: 672 2012 7 1
5782972: 672 2011 12 1
5782973: 672 2012 2 1
5782974: 672 2011 12 1
5782975: 672 2012 1 1
但是,颠倒“by”顺序会得到所需的结果。
> d[,list(n=length(trx_num)),by=list(month,year,ma)]
month year ma n
1: 12 2011 284 3
2: 1 2012 284 1
3: 11 2011 284 8
4: 5 2012 543 7
5: 7 2012 543 3
---
1214686: 5 2012 672 28
1214687: 4 2012 672 13
1214688: 12 2011 672 11
1214689: 7 2012 672 9
1214690: 9 2012 672 11
我在这里缺少什么?提前致谢。
编辑:
str() 给出错误结果的数据
> str(d)
Classes âdata.tableâ and 'data.frame': 14688135 obs. of 3 variables:
$ ma : num 3e+10 3e+10 3e+10 3e+10 3e+10 ...
$ year : int 2011 2012 2011 2011 2011 2011 2011 2011 2011 2011 ...
$ month: int 12 1 11 12 11 11 11 11 11 11 ...
- attr(*, ".internal.selfref")=<externalptr>
- attr(*, "sorted")= chr "ma"
str() 的错误结果:
> str(d[,.N,by=list(ma,year,month)])
Classes âdata.tableâ and 'data.frame': 5782975 obs. of 4 variables:
$ ma : num 3e+10 3e+10 3e+10 3e+10 3e+10 ...
$ year : int 2011 2012 2011 2011 2011 2012 2012 2012 2012 2012 ...
$ month: int 12 1 11 11 11 5 7 6 9 8 ...
$ N : int 3 1 5 1 2 1 1 1 1 1 ...
- attr(*, ".internal.selfref")=<externalptr>
和正确结果的 str() :
> str(d[,.N,by=list(month,year,ma)])
Classes âdata.tableâ and 'data.frame': 1214690 obs. of 4 variables:
$ month: int 12 1 11 5 7 6 9 8 11 12 ...
$ year : int 2011 2012 2011 2012 2012 2012 2012 2012 2011 2011 ...
$ ma : num 3e+10 3e+10 3e+10 3e+10 3e+10 ...
$ N : int 3 1 8 7 3 12 15 3 6 6 ...
- attr(*, ".internal.selfref")=<externalptr>
最佳答案
结束评论跟踪,ma
列是类型 numeric
并且包含完全不同但非常接近的值,几乎在机器公差范围内但不完全相同。换句话说,这种情况:
x < y < z
(y-x) just less than machine tolerance so considered equal
(z-y) just less than machine tolerance so considered equal
(z-x) just over machine tolerance so considered not equal
当这样的列与其他两列(即
by=
3 列)一起分组时,这 3 列的顺序(如果其中一列具有上述值)可以更改这些值是否被视为相等(并且在同一组中) ) 与否。解决方法是不使用类型
numeric
( double
是另一个名称)此类数据。使用 integer
,或者在整数大于 2^31 的情况下(导致强制转换为 double
和精度损失,iiuc),character
反而。 data.table
排序速度快 integer
和 character
.排序没那么快 double
无论如何。我们将尝试添加一个新的
warning
至 data.table
:FR#2469 Add new
tolerance.warning
option to detect and issue warning
if any numeric
values are close but not quite within machine tolerance
关于r - data.table 中的 "by"(分组依据)-我错过了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14266454/