Find the number of occurrences of a modal value for a group using data.table [R]

I used a great answer here to find a mode for groups with a data table. However, I would also like to find the number of occurrences of the modal value x for each group of variables y. How can i do this?

Edit: There is a faster way to search than in the answer above. I can’t find the answer I have (edit and add the link if you do), but it uses this function (and detects several modes if they exist):

 MultipleMode <- function(x) {
  ux <- unique(x)
  tab <- tabulate(match(x, ux)); ux[tab == max(tab)]
}

Here is a version that arbitrarily accepts only the first mode when there are two:

SingleMode <- function(x) {
  ux <- unique(x)
 ux[which.max(tabulate(match(x, ux)))]

}

, , , , , .

+4
1

, ( , ) . , , , :

mod_count_fun <- function(x) max(table(x))
DT[,modal_count := mod_count_fun(x),by=y]

, , !

: , . :

SingleModeVal <- function(x) {
 ux <- unique(x)
 max(tabulate(match(x, ux)))
}
DT[,modal_count := SingleModeVal(x),by=y]

10 , - , , .

+4

All Articles