1

I would like to subset, use an aggreate function, AND sort (descending) my table mytable with 1 short statement. For example, I am counting rows with price > 100 grouped by color, and sorting this by color descending. I have:

mytable2 <- mytable[price > 100, .N, by = color]
mytable2[order(-color)]

But I would rather have it be in one step. Something like:

mytable[price > 100, .N, keyby = color]

But this is ascending. Simply putting a - in front of color gives an error. Is there another way? Thanks.

Henrik
  • 65,555
  • 14
  • 143
  • 159
justin
  • 11
  • 2
  • 1
    Did you read [Sort a data.table fast by Ascending/Descending order](https://stackoverflow.com/questions/13685295/sort-a-data-table-fast-by-ascending-descending-order) ? – markus Mar 04 '21 at 20:11
  • I too would like to find out if possible because while `mytable2[order(-color)]` works a `keyby` solution wouldn't necessitate chaining. More succinct – Sweepy Dodo Jan 26 '23 at 15:16

1 Answers1

0

Why don't you use the chaining commands of data.table? Something like the below should serve the purpose of having it in one step.

> library(data.table)
> mytable <- data.table(price = seq(50,150,10), 
+                       color = sample(x= c("Red","Green","Blue"),size = 11,replace = T))
> 
> mytable[ price > 100,.SD ,by = .(color)][order(-color)]
   color price
1:   Red   110
2:   Red   130
3: Green   120
4: Green   150
5:  Blue   140
> ## As Color is a character variable it will be (reversely) sorted alphabatically.
Shaswata_m
  • 13
  • 5