Does this post help? mode-most-common-value-function-ignoring-na-and-returning-largest-value-in-the-event-of-a-tie/91410
From the replies I got I was able to improve my code for top 1 MostCommon. Should be possible for you to change to top N
MostCommon <- function(x) {
ux <- unique(x)
uxnotna <- ux[which(!is.na(ux))]
if(length(uxnotna) > 0) {
tab <- tabulate(match(x, uxnotna))
candidates = uxnotna[tab == max(tab)]
if (class(x)[1] == "logical") {
any(candidates) # return TRUE if any true. max returns an integer
} else {
max(candidates) # return highest (ie max) value
}
} else {
ux # this returns the NA with the right class. ie that of x
}
}