A) Instead of this (where cars <- data.table(cars)
)
cars[ , .(`Totals:`=.N), by=speed]
I need this
strColumnName <- "Totals:"
cars [ , strColumnName = .N, by=speed]
How to do it?
B) Similarly (more general case) - instead of this:
cars[ dist > 50, .(`Totals:`=.N, x=dist*100), by=speed]
I need this:
strFactor <- "dist"
cars[ strFactor > 50, .(`Totals:`=.N, x=strFactor*100), by=speed]
This question is about GENERAL way of assigning/referencing column name variables in data.table, i.e. in 'j' (both RHS and LHS), as well as in 'i' and 'by' - dynamically. This is needed when are chosen elsewhere in the code (e.g. a user my enter them in shiny app)
C) General case involving i,j and by - Instead of this:
cars[ dist > 50, .(`Totals x Factor: ` = .N * dist), by=speed]
I need this:
strFactor <- "dist";
strNewVariable <- "Totals x Factor: "
strBy <- "speed"
cars[ strFactor > 50, .(strNewVariable = .N * strFactor), by=strBy]
We can use
:=
and wrap the variable with()
to evaluate it instead of assinging it literallyIf we need a summarised column,
With the updated code
Edit: Based on your clarifications, here is an approach with
setNames
andget
. The trick here is that..
instructs the evaluation to occur in the calling environment.