Calculate Statistical mode in R

How to get mode in R? If you are new to R Programming you may not find the mode function in R as this is not present as part of the base library. In this article, I will explain how to create a mode() function, its syntax, and return type, and use it with an example.

1. Mode in R Introduction

In statistical terminology, the mode is the value that has the highest number of occurrences in a data set. So, the mode can be get from either numeric or character vectors.

Since R doesn’t have a mode base function, we need to create one. This function takes the vector as input and gives the mode value as an output.

For a character Vector, it returns a character and for a Numeric vector, it returns a numeric value.

2. Syntax of mode()

The following is the syntax of the mode() function that returns the mode value from the vector x.

mode(x, na.rm = FALSE)

2.1 Parameters

  • x – It is an input vector of type Numeric or Character
  • na.rm – Defaults to FALSE. When TRUE, it ignores NA value.

2.2 Return Value

  • Number – For numeric vector
  • Character – For character vector
  • NA – When you have NA values and not used na.rm

3 Create mode() Function

Let’s create a mode() function similar to the R median() and mean() Functions. It takes similar arguments as input. One difference is mode() takes both character or numeric vector as input.

# Create mode() function to calculate mode
mode <- function(x, na.rm = FALSE) {
  if(na.rm){ #if na.rm is TRUE, remove NA values from input x
    x = x[!]

  val <- unique(x)
  return(val[which.max(tabulate(match(x, val)))])

4. Using mode() Function in R DataFrame

Let’s create the DataFrame and use the mode() function on a column.

# Create Data Frame

# Usage of mode() Function

Yields below output.

mode in R

5. Using mode() with R Vector

Similarly, let’s also get the mode from the values of Vector in T. The following examples demonstrate getting the mode when on numeric and character vectors and also when you have NA values.

# mode() from Vector
v1 <- c(1,22,3,5,3,1)

v2 <- c("AA","BB","CC","AA","CC","CC")

v3 <- c(144,NA,144,567,567)

Yields below output.

mode example in r

6. Conclusion

In this article, you have learned that R doesn’t have a mode() function and learned how to create one with examples. And the function we created takes numeric and character function and returns a mode value.

You can find the complete example at GitHub Project.

Related Articles

Leave a Reply