1

I've been getting used to data.tables and just cannot seem to find the answer to something that feels so simple (or at least is with data frames).

I want to use data.table to aggregate, however, I don't always know which column to aggregate ahead of time (it takes input from the user). I want to define what column to use based off of a character vector. Here's a short example of what I want to do:

require(data.table)

myDT <- data.table(a = 1:10, b = 11:20, n1 = c("first", "second"))
aggWith <- "a"

Now I want to use the aggWith object to define what column to sum on. This does not work:

> myDT.Agg <- myDT[, .(Agg = sum(aggWith)), by = .(n1)]
Error in sum(aggWith) : invalid 'type' (character) of argument

Nor does this:

> myDT.Agg <- myDT[, .(Agg = sum(aggWith)), by = .(n1), with = FALSE]
Error in sum(aggWith) : invalid 'type' (character) of argument

This does:

myDT.Agg <- myDT[, .(Agg = sum(a)), by = .(n1)]

However, I want to be able to define which column "a" is arbitrarily based off a character vector. I've looking through ?data.table, but am just not seeing what I need. Sorry in advance if this is really simple and I'm just overlooking something.

1
  • 2
    use sum(get(aggWith)). Commented Dec 4, 2015 at 17:38

1 Answer 1

4

We could specify the 'aggWith' as .SDcols and then get the sum of .SD

 myDT[, list(Agg= sum(.SD[[1L]] )), by = n1, .SDcols=aggWith]

If there are multiple columns, then loop with lapply

 myDT[, lapply(.SD, sum), by = n1, .SDcols= aggWith]

Another option would be to use eval(as.name

 myDT[, list(Agg= sum(eval(as.name(aggWith)))), by = n1]
Sign up to request clarification or add additional context in comments.

4 Comments

Also get, though maybe there's some reason to prefer the eval way over that?
@Frank I used to work with eval, though I am not sure whether this has any difference in efficiency with get.
if any of them would be faster I would expect it would be eval(as.name(
This is great stuff. Thank you!

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.