3

I know we can dynamically add column names when creating columns by reference (using :=), as described e.g. here: Dynamic column names in data.table.

However, I'm looking to dynamically add column names when we aggregate. Can you help with this?

test_dtb <- data.table(a = sample(1:100, 100), b = sample(1:100, 100), id = rep(1:10, 10))
m = "blah"
test_dtb[ , list((m) = mean(b)), by = id]

The error I get is

Error: unexpected '=' in "test_dtb[ , list((m) =
5
  • 1
    Maybe this helps Commented Dec 20, 2016 at 9:55
  • I'm programmatically creating the m variable and its length can vary from 1 to 5. I think it would be hard to define which index to setnames from. Commented Dec 20, 2016 at 10:03
  • 3
    What about m = c("blah", "foo");test_dtb[,setNames(list(mean(b),median(b)), m),by = id]? Commented Dec 20, 2016 at 10:24
  • test_dtb[,eval(m):=mean(b),by = id] ? Commented Dec 20, 2016 at 17:23
  • works with multiple values also: m = c("blah", "foo"); test_dtb[,eval(m):=list(mean(b),median(b)),by = id,verbose=TRUE] gives: a b id blah foo columns Commented Dec 20, 2016 at 17:29

2 Answers 2

5

As mentioned in the comments by lukeA, setNames can be used:

m <- c("blah", "foo")
test_dtb[ , setNames(list(mean(b), median(b)), m), by = id] 
Sign up to request clarification or add additional context in comments.

Comments

-2

Just make sure data.table knows "m" is not a variable name.

Parentheses or "c" will do.

test_dtb[, (m)  := mean(b),by = id]
test_dtb[, c(m) := mean(b),by = id]

2 Comments

As I mentioned in the question, its while I'm aggregating. The answers in the comments help with that.
Woops! My mistake. In this case, the solution suggested by lukeA is an excellent one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.