Skip to content

Instantly share code, notes, and snippets.

@JosepER
Created November 29, 2019 18:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JosepER/11ed48c54a025de44230de82fb903a5b to your computer and use it in GitHub Desktop.
Save JosepER/11ed48c54a025de44230de82fb903a5b to your computer and use it in GitHub Desktop.
Mode <- function(x, tie = c("missing", "error"), ignore_categories = NULL) {
if(!is.null(ignore_categories)){
x <- x[!(x %in% ignore_categories)]
}
ux <- unique(x)
tab <- tabulate(match(x, ux))
output <- ux[tab == max(tab)]
if(length(output) == 1){
return(output)
}else if(tie == "missing"){
return(NA)
}else if(tie == "error"){
stop("There are multiple modes, and 'tie' argument was set to error.")
}else if(tie == "min"){
return(min(output))
}else if(tie == "first"){
return(output[1])
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment