I'm trying to pass an argument to a function using lapply in datatable, only the argument is a variable name (It is called in a function). The wtd.var function is from Hmisc. Example using iris:
library(Hmisc)
library(data.table)
iris <- as.data.table(iris)
weights.v ="Sepal.Length"
iris[,lapply(.SD,wtd.var,weights=weights.v),by = "Species"]
throws an error, naturally since because the variable is a string. I tried various combinations or paste0 and parse, but get() seems to do it-
iris[,lapply(.SD,wtd.var,weights=get(weights.v)),by = "Species"]
That works. But when I try to use .SDcols, it gets ignored
iris[,lapply(.SD,wtd.var,weights=weights.v),by = "Species",.SDcols=c("Petal.Length")]
Is there a better way to achieve what I'm doing?