1

I am using data.table v. 1.12.8. I am trying to refer to columns with variables, using () and get(). It fails, and I cannot understand why. This kind of syntax does work when using := and updating by reference (see this or this question).

library(data.table)
X <- data.table(id = 1:5, group = c(1,1,2,2,2), v1 = c(10,12,14,16,18), type_v1 = c("t1","t2","t1","t1","t2"))
this_var <- "v1"
X[, .("v1" = sum(v1)), by = group] # this works
X[, .((this_var) = sum(get(this_var))), by = group] # this does not

I know that for my example, I could just use .SD, but my use requires referring to columns dynamically and individually, without updating the original data.table.

roussanoff
  • 319
  • 2
  • 7

1 Answers1

1

It wouldn't work on the lhs. We can use setNames

X[, setNames(.(sum(get(this_var))), this_var), by = group] 

Or setnames after that

setnames(X[,  sum(.SD[[1]]), by = group, .SDcols = this_var], 'V1', this_var)[]

-output

#   group v1
#1:     1 22
#2:     2 48
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Interesting. Is there some reasoning behind why data.table treats LHS differently depending on whether it's a `:=` or a `=` expression, and so setNames has to be used in the latter case? – roussanoff Sep 30 '20 at 22:58
  • @roussanoff Generally the `=` would evaluate the name literally instead of the value stored in that object. – akrun Sep 30 '20 at 22:59