Skip to content

Instantly share code, notes, and snippets.

@emraher
Created November 1, 2017 08:13
Show Gist options
  • Save emraher/274850527aaacd997fa2b8fa1fc0de5b to your computer and use it in GitHub Desktop.
Save emraher/274850527aaacd997fa2b8fa1fc0de5b to your computer and use it in GitHub Desktop.
Mode function for R
# SEE
# https://myrgiovanni.blogspot.com.tr/2016/07/computing-mode-in-r.html
# https://stackoverflow.com/a/25635740
# https://stackoverflow.com/a/22123729
Mode <- function(x, na.rm = FALSE, mult = TRUE) {
if(na.rm) {
x = x[!is.na(x)]
}
ux <- unique(x)
A <- tabulate(match(x, ux))
if(isTRUE(mult)) {
return(ux[A == max(A)])
} else {
return(ux[which.max(A)])
}
}
MaxTable <- function(InVec, mult = FALSE) {
if (!is.factor(InVec)) InVec <- factor(InVec)
A <- tabulate(InVec)
if (isTRUE(mult)) {
levels(InVec)[A == max(A)]
}
else levels(InVec)[which.max(A)]
}
#One mode
fruit = c(rep("apple", 10), rep("pear", 5), rep("banana", 2))
Mode(fruit)
MaxTable(fruit)
# [1] "apple"
#Two modes
fruit2 = c(rep("apple", 5), rep("pear", 5), rep("banana", 2))
Mode(fruit2)
MaxTable(fruit2, mult = T)
# [1] "apple" "pear"
#No mode
fruit3 = c(rep("apple", 5), rep("pear", 5), rep("banana", 5))
Mode(fruit3)
MaxTable(fruit3, mult = T)
# [1] NA
#One mode
count1 = c(rep(1, 10), rep(2, 5), rep(3, 2))
Mode(count1)
MaxTable(count1)
# [1] 1
#Two modes
count2 = c(rep(1, 5), rep(2, 5), rep(3, 2))
Mode(count2)
MaxTable(count2, mult = T)
# [1] 1 2
#No mode
count3 = c(rep(1, 5), rep(2, 5), rep(3, 5))
Mode(count3)
MaxTable(count3)
MaxTable(count3, mult = T)
# [1] NA
#NAs
count4 <- c(rep(1, 5), rep(NA, 5), rep(3, 2))
Mode(count4)
MaxTable(count4)
MaxTable(count4, mult = T)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment