Function to Calculate Mode in R
Sample Data Set (Vector)
vec <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 3)
print(vec)
## [1] 1 2 3 4 5 6 7 8 9 3
Method 1 (Using library modeest)
library(modeest)
##
## This is package 'modeest' written by P. PONCET.
## For a complete list of functions, use 'library(help = "modeest")' or 'help.start()'.
mlv(vec, method = "mfv")
## Mode (most likely value): 3
## Bickel's modal skewness: 0.4
## Call: mlv.default(x = vec, method = "mfv")
Method 2 (Function to find mode)
# Function to find mode
Find_Mode <- function(x) {
unique_val <- unique(x) # Find unique values in the vector
# Check to determine whether mode exist or not
if (length(x)==length(unique_val)) {
mode_x <- 'Mode does not exist'
return(mode_x)
}
# Create freq vector to keep track of number of occurences of a value
freq <- rep(0, length(unique_val))
# For loop to update the number of occurences
for (i in 1:length(unique_val)) {
for (j in 1:length(x)) {
if (unique_val[i]==x[j]) {
freq[i] = freq[i] + 1;
}
}
}
# Check to determine whether mode exist or not
if (mean(freq)==max(freq)) {
mode_x <- 'Mode does not exist'
return(mode_x)
}
# Find and return the mode
idx <- which.max(freq)
mode_x <- unique_val[idx]
return(mode_x)
}
# Find mode of vec
Find_Mode(vec)
## [1] 3
Method 3 (Alternative Function to find mode)
Find_Mode2 <- function(x) {
ux <- unique(x)
# Check to determine whether mode exist or not
if (length(x)==length(ux)) {
mode_x <- 'Mode does not exist'
return(mode_x)
}
# Finding the number of occurences
tab <- tabulate(match(x, ux))
# Check to determine whether mode exist or not
if (mean(tab)==max(tab)) {
mode_x <- 'Mode does not exist'
return(mode_x)
}
# Find and return the mode
idx <- which.max(tab)
mode_x <- ux[idx]
return(mode_x)
}
Find_Mode2(vec)
## [1] 3