To find the element with the maximum number of occurrences in a list in R, you can use the table
function.
In this example,
data
with several elements.table
function to count the occurrences of each element in the vector and store the result in count
.which.max
function on the count
object, which returns the name of the most common element.data <- c(1, 2, 2, 3, 3, 3, 4)
count <- table(data)
most_common_element <- names(which.max(count))
cat("Element with the maximum occurrences is:", most_common_element)
Element with the maximum occurrences is: 3
In this example,
words
with several string elements.table
function to count the occurrences of each string in the vector and store the result in count
.which.max
function on the count
object, which returns the name of the most common element.words <- c("apple", "banana", "apple", "orange", "banana", "apple")
count <- table(words)
most_common_word <- names(which.max(count))
cat("String with the maximum occurrences is:", most_common_word)
String with the maximum occurrences is: apple
In this tutorial, we learned How to find the Element with Maximum Number of Occurrences in a List in R language with well detailed examples.