How To Find Mode In R

The mode in R is the value with the most occurrences in a vector or column of a data frame (including numeric and string values). This article will share how to find mode in R. Let’s get started.

Table of Contents

How to find mode in R

The R language does not provide any specific function to find the mode of a vector or a data frame. We give the following solution to find mode in R.

First, we use the unique() function to find and remove duplicates from the input data.

Then we use the match() function to get the index of each input vector element in the vector just returned by the unique() function.

Next, we use the tabulate() function on the vector generated by the match() function. The tabulate() function returns a numeric vector consisting of the number of occurrences of each integer in the input vector.

Syntax:

tabulate(bin, nbins)

Parameters:

bin: a vector of numbers.

nbins: the number of bins to be used.

Example:

input <- c(1, 0, 2, 3, 3, 0, 3, 3, 3, 0, 0, 4, 4, 5)

# Remove duplicates
uniq <- unique(input)
uniq

# Index of each input vector element in the 'uniq' vector.
index <- match(input, uniq)
index

# Number of occurrences of each integer in the 'index' vector
num_occur <- tabulate(index)
num_occur

Output:

[1] 1 0 2 3 4 5
 [1] 1 2 3 4 4 2 4 4 4 2 2 5 5 6
[1] 1 4 1 5 2 1

The mode to look for is the value of the deduplicated vector whose index is equal to the index of the maximum value in the vector returned by the tabulate() function.

From the above steps, we build a reusable function.

Completed code:

mode <- function(input) {
    uniq <- unique(input)
    num_occur <- tabulate(match(input, uniq))
    uniq[num_occur == max(num_occur)]
}

The following simple example will show you how this function works.

Example:

# Find mode in R
mode <- function(input) {
    uniq <- unique(input)
    num_occur <- tabulate(match(input, uniq))
    uniq[num_occur == max(num_occur)]
}

# Create a numeric vector
num <- c(1, 0, 2, 3, 3, 0, 3, 3, 3, 0, 0, 4, 4, 5)

# Create a character vector
lang <-
    c(
        "JavaScript",
        "R",
        "Java",
        "R",
        "R",
        "JavaScript",
        "Python",
        "Python",
        "R",
        "JavaScript"
    )

cat("Mode of the numeric vector: ")
mode(num)

cat("Mode of the character vector: ")
mode(lang)

Output:

Mode of the numeric vector: [1] 3
Mode of the character vector: [1] "R"

Summary

There isn’t any specific function to find the mode in R. In this article, we have built a function that includes some simple functions in R to find mode. Hope this is helpful to you. Thank you for reading.

Posted in R

Leave a Reply

Your email address will not be published. Required fields are marked *