Extract Most Common Values from Vector in R (Example)


In this R tutorial you’ll learn how to select the most frequent elements of a vector or data frame variable.

Table of contents:

Let’s dive right into the example!


Creation of Example Data

We use the following data as basement for this R programming tutorial.

vec <- c("A", "B", "B", "C", "F",           # Create example vector
         "A", "D", "F", "A", "E")
vec                                         # Print example vector
# [1] "A" "B" "B" "C" "F" "A" "D" "F" "A" "E"

The previously shown output of the RStudio console shows that the exemplifying data is a character vector containing of different letters.


Example: Return Most Frequent Values from Vector Using table() & sort() Functions

In this example, I’ll explain how to select the most common elements from a vector using the table and sort functions in R.

Let’s first apply the table function to see the count of all elements in our vector:

table(vec)                                  # Apply table function
# vec
# A B C D E F 
# 3 2 1 1 1 2

The previous output of the RStudio console shows the frequency of all values in our data.

Next, we can combine the table function with the sort function to return only the N most common values of our vector:

sort(table(vec), decreasing = TRUE)[1:3]    # Extract most common value
# vec
# A B F 
# 3 2 2

The letters A, B, and F are the most frequent values.

Note that we could apply the same type of code to the column of a data frame.


Video, Further Resources & Summary

Do you need more information on the R programming syntax of this page? Then you might want to watch the following video of my YouTube channel. In the video, I show the content of this tutorial:



In addition, you may read some of the related articles on this website. Some interesting tutorials about related topics such as vectors, missing data, and data elements are shown below:


In this R tutorial you have learned how to extract common elements from columns and vectors. In case you have additional questions, don’t hesitate to let me know in the comments section. In addition, please subscribe to my email newsletter to receive updates on new posts.


Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.

Leave a Reply

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

Fill out this field
Fill out this field
Please enter a valid email address.