0

Right off the bat, I'm not referring to this question. That question deals with an update by reference kind of scenario. However, if I have still missed a question, I am sorry, please close this question.

Here is what I am talking about.

library(data.table)
x <- setDT(copy(mtcars))
# This is possible
x[, .(mpg = mean(mpg)), keyby = cyl]

colName <- 'mpg'
# How to achieve something like this?
x[, .((colName) = mean(mpg)), keyby = cyl]

Is there some way to make (colName) work in this case? To be clear, I do not want to update x, but want to assign the column name directly to the newly created data.table.

Ameya
  • 1,712
  • 1
  • 14
  • 29
  • 3
    `x[, (colName) := .(mean(mpg)), keyby = cyl]` or `x[, setNames(.(mean(mpg)), colName), keyby=cyl]`? – chinsoon12 May 30 '18 at 02:38
  • Sorry, should have been clear. I do not want to update `x`. But instead want to create a new `data.table`. – Ameya May 30 '18 at 02:39
  • Thanks, do you want to add that as an answer? Although I still thought there'd be an elegant way do it than resort to `setNames`. – Ameya May 30 '18 at 02:43
  • i think this is a dupe. Hence, you might want to close it. – chinsoon12 May 30 '18 at 02:59
  • @zacdav That does not work, I would have thought something like that would work. That returns an error. – Ameya May 30 '18 at 03:01
  • @chinsoon12. Of which question would this be a dupe of? I'll be happy to close it if you can point me to the correct question. – Ameya May 30 '18 at 03:03
  • for eg. https://stackoverflow.com/questions/49230351/naming-a-column-in-a-list-manner-with-string-in-data-table/49230383#49230383 I rem there is a few more – chinsoon12 May 30 '18 at 03:05
  • @chinsoon12 Have voted to close. Thank you! – Ameya May 30 '18 at 03:07

0 Answers0