Say I want to create a function that calculates a summary dataset from a data.table in R, and I want to be able to pass the name of the new calculated variable in programmat
Courtesy of docendo discimus, you can use a named list created with setNames, like this:
setNames
groupMeans <- function(out.var, by.var, dat = dt) { return(dat[, setNames(list(mean(x)), out.var), by = by.var]) } groupMeans("group.means", "by.var") # by.var group.means # 1: a -0.1159832 # 2: b 0.2910531