Assigning/Referencing a column name in data.table dynamically (in i, j and by)

后端 未结 2 552
感情败类
感情败类 2021-01-06 05:14

A) Instead of this (where cars <- data.table(cars))

cars[ , .(`Totals:`=.N), by=speed]  

I need this

strCo         


        
2条回答
  •  长情又很酷
    2021-01-06 05:35

    Edit: Based on your clarifications, here is an approach with setNames and get. The trick here is that .. instructs the evaluation to occur in the calling environment.

    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] 
    

提交回复
热议问题