How To Calculate Mode In R

Mode, while not exactly one of the measures of central tendency, can be an extremely helpful number to have in statistical analysis. Many analytical procedures require you to find the mode of a distribution – the value which occurs most commonly. You can use R to find which numerical vectors occur most commonly in your data, which can help you draw inferences and make predictions about future data. While R does not have a built in function for calculating the mode, this can be easily solved with a little code.

How To Find The Mode in R

Simple answer: we’re going to count the number of times a value occurs within a vector and pick the largest.

# calculate mode in r example
# mode calculation function
test <- c(1,2,3,4,5,5,5,5,3,2,3,1,1,2)

getMode <- function(x) {
keys <- unique(x)
keys[which.max(tabulate(match(x, keys)))]
}

How It Works (find mode in R)

how to calculate mode in r  mode on a histogram in r  mode calculation function in r  r mode calculation  how to get the mode in r

Our getMode function splits the problem into two parts.

The first extracts the unique values in our vector and places them in an array called keys.

The second line of code, using the which.max tabulate match function, counts the number of time each key occurs and selects the largest one. The function returns the value which occurs the most, and that is your mode.

Calculate Mode in R – Missing Values

One quirk – if you’re dealing with a sparse data-set where many values are missing, this may throw the calculation off. It could tell you that the most common variable is missing – which may be be true – technically. If you want the largest non-missing value, we’re going to add the omit function (na omit). You could also potentially use the complete.cases function to deal with your missing data.

# calculate mode in r	
getMode <- function(x) {
keys <- na.omit(unique(x))
keys[which.max(tabulate(match(x, keys)))]
}

This is worth dropping into your desktop file or standard library.

Calculating mode in R is relatively simple, even though it is not a standard R function. You will likely use this mode calculation function for the rest of your programming career, so it is good to learn how to calculate mode in R now. We hope our R mode tutorial was helpful, and encourage you to check out our other helpful tips for statistical operations in R:

Scroll to top
Privacy Policy