1

How to summarize a data.table creating new column whose name comes from a string or character?

reproducible example:

library(data.table)

dt <- data.table(x=rep(c("a","b"),20),y=factor(sample(letters,40,replace=T)), z=1:20)

i <- 15
new_var <- paste0("new_",i)

# my attempt
dt[, .( eval(new_var) = sum( z[which( z <= i)] )), by= x]

# expected result
dt[, .( new_15 = sum( z[which( z <= i)] )), by= x]

>    x new_15
> 1: a    128
> 2: b    112

This approach using eval() works fine for creating a new column with := (see this SO questions), but I don't know why it does not work when summarizing a data.table.

rafa.pereira
  • 13,251
  • 6
  • 71
  • 109

1 Answers1

1

One option is setNames

dt[, setNames(.(sum( z[which( z <= i)])), new_var) , by= x]
#   x new_15
#1: a    128
#2: b    112
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Thank you for reply @akrun, it works really well when I'm only summarizing one column. However, it doesn't work when I try to summarize more columns at the same time. For example: `dt[, .( other_var = mean(z) , setNames( sum( z[which( z <= i)]), new_var)) , by= x] ` – rafa.pereira Jan 09 '18 at 22:28
  • 1
    @rafa.pereira You need to place the `setNames` outside the `.(` – akrun Jan 10 '18 at 03:24