0

I want to count how many rows are equal to the max value within a group (in data.table). I know from Select the row with the maximum value in each group how to find the max value in data.table.

set.seed(5)
z <- data.table( data.frame(
    group=( sample( letters[1:5], 25,  replace=T) ),
    size=( sample( 1:5, 25,  replace=T) )))

z <- z[ order( group, size ), ]

z[ , maxsize := max(size), by = .(group)]

So in this example, I want a column equal to 2 for group a, (since there are two observations equal to 3) and 4 for b, 2 for c etc.

enter image description here

MatthewR
  • 2,660
  • 5
  • 26
  • 37
  • Related: [Count number of rows matching a criteria](https://stackoverflow.com/questions/28195996/count-number-of-rows-matching-a-criteria) – Henrik Mar 03 '23 at 15:09

1 Answers1

0

When a logical vector is summed the TRUE/FALSE values will be regarded as 1/0 so sum size == max(size) by group.

z[, count_max := sum(size == max(size)), by = group]

Alternately, in base R we could use ave

transform(z, count_max = ave(size, group, FUN = \(x) sum(x == max(x))))
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341