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

后端 未结 2 549
感情败类
感情败类 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:22

    We can use := and wrap the variable with () to evaluate it instead of assinging it literally

    library(data.table)
    cars[ , (strColumnName) := .N, by=speed]  
    

    If we need a summarised column,

    setnames(cars[, .N, by = speed], 'N',  strColumnName)[]
    

    With the updated code

    cars[eval(as.name(strFactor)) > 50, .(`Totals:`=.N, x=eval(as.name(strFactor))*100), by=speed]
    
    0 讨论(0)
  • 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] 
    
    0 讨论(0)
提交回复
热议问题