动态分配/引用 data.table 中的列名(在 i、j 和 by 中)

IVI*_*VIM 4 r data.table

A) 而不是这个 (where cars <- data.table(cars))

cars[ , .(`Totals:`=.N), by=speed]  
Run Code Online (Sandbox Code Playgroud)

我需要这个

strColumnName <- "Totals:"
cars [ , strColumnName = .N, by=speed]  
Run Code Online (Sandbox Code Playgroud)

怎么做?

B)类似(更一般的情况) - 而不是这个:

cars[ dist > 50, .(`Totals:`=.N, x=dist*100), by=speed] 
Run Code Online (Sandbox Code Playgroud)

我需要这个:

strFactor <- "dist"
cars[ strFactor > 50, .(`Totals:`=.N, x=strFactor*100), by=speed] 
Run Code Online (Sandbox Code Playgroud)

这个问题是关于在 data.table 中分配/引用列名变量的一般方法,即在“j”(RHS 和 LHS)以及“i”和“by”中 - 动态。当在代码中的其他地方选择时这是必需的(例如,用户我在闪亮的应用程序中输入它们)

C) 涉及 i,j 和 by 的一般情况 - 而不是这样:

 cars[ dist > 50, .(`Totals x Factor: ` = .N * dist), by=speed] 
Run Code Online (Sandbox Code Playgroud)

我需要这个:

strFactor <- "dist"; 
strNewVariable <- "Totals x Factor: "
strBy <- "speed"
cars[ strFactor > 50, .(strNewVariable = .N * strFactor), by=strBy] 
Run Code Online (Sandbox Code Playgroud)

Ian*_*ell 8

编辑: 根据您的说明,这是一种使用setNamesand的方法get。这里的技巧是..指示评估发生在调用环境中。

library(data.table)
cars <- data.table(cars)
strFactor <- "dist"
strNewVariable <- "Totals x Factor: "
strBy <- "speed"
cars[ get(strFactor)  > 50, 
     setNames(.(.N * get(..strFactor)),strNewVariable),
     by=strBy] 
Run Code Online (Sandbox Code Playgroud)