'R data.table best way to modify dynamically selected columns

I have a data.table DT which contains many columns. I have to assign percentages of dynamically selected set of columns (stored in string vector 'percentVars') with respect to another column called 'Awake' to themselves. I have tried following expressions.

# I am a Matlab user and new to R. This is R equivalent of how I would do this in Matlab
DT[,percentVars]=DT[,(percentVars)]/DT$Awake*100

#looks elegant, and perhaps more efficient?
DT[,(percentVars):= .SD/Awake*100, .SDcols=percentVars]

#why I see people always use lapply with := operator, what's the difference compared to above?
DT[,(percentVars):= lapply(.SD, function(z) z/Awake*100), .SDcols=percentVars]

# otherwise loop over percentVars with set?
for (col in percentVars) set(DT,,col,DT[,..col]/DT$Awake*100)

Which expression is better (memory and computational efficient, works by reference, vectorized etc)? Is there a better way to do this?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source