使用 data.table
时包,我有点不确定何时需要 setkey()
.例如,当使用 :=
带有 by
的运算符选项,即使我没有设置 key ,事情似乎仍然非常快。有人可以解释一下setkey()
是必要的,什么时候不需要?如果在调用 :=
之前没有必要与 by
那么 data.table
怎么样?包这么快,因为大概它必须做与 apply
相同的事情在标准 data.frame
R 通过执行顺序搜索而不是二进制搜索,因为它不知道我的 data.table
实际上是按 by
的参数排序的.
谢谢
最佳答案
这 2 个常见问题解答似乎很接近:
3.2 I don't have a key on a large table, but grouping is still really quick. Why is that?
data.table
uses radix sorting. This is signicantly faster than other sort algorithms. Radix is specifically for integers only, see?base::sort.list(x,method="radix")
. This is also one reason whysetkey
is quick. When no key is set, or we group in a different order from that of the key, we call it an ad hoc by.3.3 Why is grouping by columns in the key faster than an ad hoc by?
Because each group is contiguous in RAM, thereby minimising page fetches, and memory can be copied in bulk (memcpy
in C) rather than looping in C.
它没有说并且可能应该做的是,在您注意到 keyed by 和 ad hoc by 之间的区别之前,您需要一个非常大的数据集,其中每个组也非常大。类似于 100 组,每组 100MB(一个 10GB 的 data.table),例如 1e8 行和 13 列。否则不需要
setkey
首先,特别是因为这可能会变得繁重。
关于r - setkey 和 := operator, 数据表,R,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11584648/