1

I'm using R's data table, and am trying to assign a column with := named with a character object while performing an operation by group.

If it's not done by group, things are relatively straightforward:

dt <- data.table(mtcars)[, .(cyl, mpg)]

thing2 <- 'mpgx2'
dt[,(thing2):=mpg*2]

However, when I'm doing things by group, an error occurs:

DT <- data.table(V1=c(1L,2L),
                 V2=LETTERS[1:3],
                 V3=round(rnorm(4),4),
                 V4=1:12)

ghi <- "def"

DT[,.((ghi)=mean(V3)),by=V1]

Specifically, Error: unexpected '=' in "DT[,.((ghi)=".

How can I rectify this?

wwl
  • 2,025
  • 2
  • 30
  • 51

1 Answers1

3

We can use setNames

DT[,setNames(.(mean(V3)), ghi), by = V1]
#   V1     def
#1:  1 -1.4663
#2:  2  0.0414
akrun
  • 874,273
  • 37
  • 540
  • 662
  • 1
    Thanks, this is great! Just a note to future readers that setNames should not be confused with setnames, the latter being a data.table function. – wwl Jun 18 '18 at 21:15