Search code examples
rdata.tableevaldynamic-columns

dynamic column names seem to work when := is used but not when = is used in data.table


Using this dummy dataset

setDT(mtcars_copy<-copy(mtcars))
new_col<- "sum_carb" # for dynamic column referencing

Why does Case 1 work but not Case 2?

# Case 1 - Works fine
mtcars_copy[,eval(new_col):=sum(carb)] # Works fine


# Case 2:Doesnt work
aggregate_mtcars<-mtcars_copy[,(eval(new_col)=sum(carb))] # error
aggregate_mtcars<-mtcars_copy[,eval(new_col)=sum(carb))] # error
aggregate_mtcars<-mtcars_copy[,c(eval(new_col)=sum(carb))] # Error

How does one get Case 2 to work wherein I dont want the main table (mtcars_copy in this case to hold the new columns) but for the results to be stored in a separate aggregation table (aggregate_mtcars)


Solution

  • One option is to use the base R function setNames

    aggregate_mtcars <- mtcars_copy[, setNames(.(sum(carb)), new_col)]
    

    Or you could use data.table::setnames

    aggregate_mtcars <- setnames(mtcars_copy[, .(sum(carb))], new_col)