R - Count the Most Frequent Element in a Vector

R 语言实例R Language Examples

In the following example, we use a custom function to find the element that appears most frequently in a vector.

Example

# Create a vector
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 the result
result <- getmode(v)
print(result)

# String vector
charv <- c("google","example","taobao","example","example")

# Calculate the result
result <- getmode(charv)
print(result)

Executing the above code produces the following result:

[1] 2
[1] "example"

R 语言实例R Language Examples

Other Extensions