【发布时间】:2015-03-12 23:21:37
【问题描述】:
我有两个真实的data.table 代码示例,它们可以正常工作,但似乎消耗的内存比我预期的要多,我非常感谢有关如何使这段代码更节省内存的想法。
A = data.table(a=c(rep(1,5),rep(2,5)), b1=2:11, b2=22:31, c=c(1,2,1,2,1,2,1,2,1,2))
# Example 1:
# Pick the column name (b1 or b2) based on the value in column a
# and assign the value from <b1 or b2> by reference to column res
setkey(A, a, c)
A[, res:=get(paste0("b", a)), by=c("a", "c")]
# Example 2:
# Group the values of A by key, saving the following:
# 1) number of values in column res that meet some condition
# 2) the minimum value of column a
setkey(A, c)
z = A[, list(length(.I[res>5]), min(res)), by=c]
我使用lineprof 使用更大的真实数据对它们进行了测试,在整个使用data.tables 的代码中它们是异常值。
# This is more like the real size of the data I'm dealing with
A = data.table(a=c(rep(1,5e6),rep(2,5e6)),
b1=1:5e6, b2=(5e6+1):10e6,
c=round(runif(1e7, min=1, max=2)))
任何建议将不胜感激!
【问题讨论】:
-
感谢@David 的编辑 - 很好发现!
-
我认为第二个问题你可以做
A[, .(sum(res>5), min(res)), by=c] -
您也不应该在每次迭代中调用 paste,您可以使用
do.call调用一次,然后仅在get上迭代,例如A[, temp := do.call(paste0, list("b", a))][, res := get(temp), .(a, c)]虽然 mnel 二进制搜索会更多高效。 -
@mnels 二进制连接不是更有效吗?我不明白。
-
您的
data.table版本是什么?当前开发1.9.5中修复了一些不需要的泄漏(来自 1.9.2/1.9.4)。
标签: r data.table