R - Finding the Most Frequent Element in a Vector
In the following example, we create a custom function to find the element that appears most frequently in a vector.
Example
# Create a function
getmode <- function(v) {
uniqv <- unique(v)
uniqv[which.max(tabulate(match(v, uniqv)))]
}
# Numeric vector
v <- c(2,1,2,3,1,2,3,4,1,5,5,3,2,3)
# Calculate result
result <- getmode(v)
print(result)
# Character vector
charv <- c("google","tutorialpro","taobao","tutorialpro","tutorialpro")
# Calculate result
result <- getmode(charv)
print(result)
Executing the above code produces the following output:
[1] 2
[1] "tutorialpro"