I have a data.table and I want to multiply all the values in column 1 by the first element of a vector, then multiply all the values in column 2 by the 2nd element of the vector, etc...
dt <- data.table(col1=c(1,1,1,1), col2=c(2,2,2,2), col3=c(3,3,3,3))
v <- c(1,2,3)
For a data.frame I would do
dt.new <- sapply(1:ncol(dt), function(i) dt[, i] * vec[i])
But it doesn't work like this for data.table. I tried
cols <- c("col1", "col2", "col3")
dt.new <- dt[, (cols):= lapply(.SD, function(i) dt[[i]]*v[i]), .SDcols = cols]
It does not work either. How can I do this?