如何在data.table中按组操作为列编写可重用函数?

时间:2016-08-26 16:48:42

标签: r data.table

在许多data.tables中我需要一些列(~20),如何在函数中封装操作?

例如,我想在每个data.table中都有列a1a2,最快的方法是复制和粘贴代码:

n= 10
m = 2
d = data.table( p = c(1:n)*1.0, q = 1:m)
dnew = d[, list(a1 = mean(p),a2 = max(p), b = 2) , by = q] #copy and paste

我想写这样的可重用函数,

f <- function(d) with(d, list( a1 = mean(p), a2 = max(p))) #return list
dnew = d[, c(f(.SD), list( b = 2)) , by = q]

或者,

g <- function(d)d[, list(a1 = mean(p), a2 = max(p)), by = q] #return data.table
dnew1 = g(d)
dnew2 = d[, list(b = 2),by = q]
dnew = merge(dnew1, dnew2, by = "q")

但是,当组数(m)非常大时,两者都非常慢。

1 个答案:

答案 0 :(得分:5)

好的,您可以关注the metaprogramming help from FAQ 1.6

# expression instead of a function
fe = quote(list(a1 = mean(p), a2 = max(p)))

# add another element
e = fe
e$b = 2

# eval following FAQ
d[, eval(e), by=q]

我从Hadley Wickham's notes on expressions借用了e$b = 2语法。

这确实有效,但查看d[, eval(e), by=q, verbose=TRUE]我们发现max没有得到优化。由于b只是一个常量,我会在第二步中添加它:

extrae = quote(`:=`(b = 2))
d[, eval(fe), by=q][, eval(extrae)][]

# or if working interactively...
d[, eval(fe), by=q][, b := 2][]

使用verbose=TRUE,我们现在会看到fe已优化为list(gmean(p), gmax(p))