2

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?

vagabond
  • 3,288
  • 4
  • 40
  • 74
Ozeuss
  • 119
  • 6

1 Answers1

0

A simple (but probably sub-optimal) workaround would be to sapply by subsets...

sapply(levels(iris$Species), function(x) {with(subset(iris,
Species==x),wtd.var(Petal.Length,Sepal.Length))})

Hope this helps.

GPP
  • 46
  • 6