我一直在使用以下格式的 dplyr 代码
group_by(dt, ID) %>%
filter(any(colY == 1 & colX == 10))
像下面这样对 data.table 进行子集化
ID colX colY 1111 3 1 1111 2 1 1111 6 0 1111 9 0 2222 10 1 2222 3 1 2222 5 0 2222 7 0 3333 8 1 3333 10 1 3333 3 0 3333 2 0
into
ID colX colY 2222 10 1 2222 3 1 2222 5 0 2222 7 0 3333 8 1 3333 10 1 3333 3 0 3333 2 0
Filtering through about 900k rows to get the second table takes about 1.3 seconds.
I have been trying to implement a data.table subset that would be faster, but so far the results have only taken longer. Using the following data.table subset
dt[ , .SD[any( (colY == 1 & colX == 10)) ], ID]
大约需要 14 秒。这里似乎有什么问题?
最佳答案
这可能会更快。它避免使用 .SD
并使用 .I
中给出的行号。
dt[dt[, .I[any(colX == 10 & colY == 1)], by = ID]$V1]
# ID colX colY
# 1: 2222 10 1
# 2: 2222 3 1
# 3: 2222 5 0
# 4: 2222 7 0
# 5: 3333 8 1
# 6: 3333 10 1
# 7: 3333 3 0
# 8: 3333 2 0
内部数据表调用 dt[, .I[any(colX == 10 & colY == 1)], by = ID]$V1
为我们提供了这些组的行号符合我们的条件。 .I
为我们提供了每个组的行位置。我们可以通过打印我们的调用来查看结果:
dt[, print(.I[any(colX == 10 & colY == 1)]), by = ID]
# integer(0)
# [1] 5 6 7 8
# [1] 9 10 11 12
# Empty data.table (0 rows) of 1 col: ID
然后我们只使用该结果作为原始数据表上的行子集。
关于r - 缓慢的 data.table 子集与 dplyr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46638058/