I need help to remove a loop in a function using data table.
The code:
f = function(DT, col_by, col_func, col_new, func){
temp = DT[, mget(unique(c(col_by,col_func)))]
##loop to remove
for ( i in 1:length(func)){
temp[ ,eval(col_new[i]) := do.call(func[[i]], lapply(col_func, function(x) get(x))), by = mget(col_by)]
}
##
temp = unique(temp[,mget(c(col_new, col_by))])
return(temp)
}
DT = data.table(iris)
col_by = c("Species")
col_func = c("Petal.Length","Petal.Width")
col_new = c("PL.mean","PL.max")
func = list(function(x,y) return(mean(x[y == max(y)])), function(x,y) return(max(x[y == max(y)])))
f(DT, col_by, col_func,col_new,func)
If you have any idea to used data table tricks to remove this loop, let me know!
Thanks a lot for your help :)