To find the item with the maximum number of occurrences in a Vector in R, you can use the table
function to count the occurrences of each item and then find the item with the maximum count.
In this example,
vec
with several elements.table
function to create a frequency table of the elements in the vector. The table
function counts the occurrences of each unique element and returns an object of class table
.which.max
function to find the element of the frequency table with the highest count. The which.max
function returns the index of the first maximum value in a numeric vector.which.max
.vec <- c('apple', 'banana', 'apple', 'orange', 'banana', 'apple')
# Step 2: Create a frequency table
freq_table <- table(vec)
# Step 3: Find the item with the maximum occurrences
max_item <- names(which.max(freq_table))
# Step 4: Print the item
cat('Item with maximum occurrences:', max_item, '\n')
Item with maximum occurrences: apple
In this example,
vec
with several elements.table
function to create a frequency table of the elements in the vector. The table
function counts the occurrences of each unique element and returns an object of class table
.which.max
function to find the element of the frequency table with the highest count. The which.max
function returns the index of the first maximum value in a numeric vector.which.max
.vec <- c(1, 2, 3, 1, 2, 1, 4, 1, 5, 1)
# Step 2: Create a frequency table
freq_table <- table(vec)
# Step 3: Find the item with the maximum occurrences
max_item <- names(which.max(freq_table))
# Step 4: Print the item
cat('Item with maximum occurrences:', max_item, '\n')
Item with maximum occurrences: 1
In this tutorial, we learned How to find the Item with Maximum Number of Occurrences in a Vector in R language with well detailed examples.