在许多data.tables中我需要一些列(~20),如何在函数中封装操作?
例如,我想在每个data.table中都有列a1
和a2
,最快的方法是复制和粘贴代码:
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)非常大时,两者都非常慢。
答案 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))
。