Tim Hoolihan
Tim Hoolihan

Reputation: 12396

Sort by aggregation in data.table

Can you order by an aggregation in data.table?

I can do it in two lines as follows:

mbc <- flights[, .(miles = sum(distance)), by = "carrier"]
setorder(mbc, -miles)

But it feels like I'm missing something and this should be possible in indexing data.table. However, the following produces an error:

mbc <- flights[order(-miles), .(miles = sum(distance)), by = "carrier"]

I'm not really obsessed with it being one line, but more trying to make sure I understand data.table aggregations.

Upvotes: 1

Views: 801

Answers (1)

Tim Hoolihan
Tim Hoolihan

Reputation: 12396

Per @David Arenburg's comment above, a double index works.

mbc <- flights[, .(miles = sum(distance)), by = "carrier"][order(-miles)]

Upvotes: 1

Related Questions