【发布时间】:2015-02-15 04:13:08
【问题描述】:
如果我在 datatable 之上使用 dplyr 语法,我能否在使用 dplyr 语法的同时获得 datatable 的所有速度优势?换句话说,如果我使用 dplyr 语法查询它,我是否误用了数据表?还是我需要使用纯数据表语法来利用它的所有功能。
提前感谢您的任何建议。代码示例:
library(data.table)
library(dplyr)
diamondsDT <- data.table(ggplot2::diamonds)
setkey(diamondsDT, cut)
diamondsDT %>%
filter(cut != "Fair") %>%
group_by(cut) %>%
summarize(AvgPrice = mean(price),
MedianPrice = as.numeric(median(price)),
Count = n()) %>%
arrange(desc(Count))
结果:
# cut AvgPrice MedianPrice Count
# 1 Ideal 3457.542 1810.0 21551
# 2 Premium 4584.258 3185.0 13791
# 3 Very Good 3981.760 2648.0 12082
# 4 Good 3928.864 3050.5 4906
这是我想出的数据表等效项。不确定它是否符合 DT 良好实践。但是我想知道代码是否真的比幕后的dplyr语法更高效:
diamondsDT [cut != "Fair"
] [, .(AvgPrice = mean(price),
MedianPrice = as.numeric(median(price)),
Count = .N), by=cut
] [ order(-Count) ]
【问题讨论】:
-
为什么不用数据表语法?它既优雅又高效。这个问题很难回答,因为它非常广泛。是的,数据表有
dplyr的方法,但数据表也有自己的可比方法 -
我可以使用数据表语法或课程。但不知何故,我发现 dplyr 语法更优雅。不管我对语法的偏好如何。我真正想知道的是:我是否需要使用纯数据表语法才能获得 100% 的数据表功能优势。
-
对于最近在
data.frames 和相应的data.tables 上使用dplyr的基准,请参阅here(以及其中的引用)。 -
@Polymerase - 我认为这个问题的答案肯定是“是”
-
@Henrik:我后来意识到我误解了那个页面,因为它们只显示了数据框构造的代码,而不是它们用于 data.table 构造的代码。当我意识到这一点时,我删除了我的评论(希望你没有看到它)。
标签: r data.table dplyr