To find the item with the minimum 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 minimum count.
In this example,
vec
containing several string elements.table
function to count the occurrences of each string in the vector. This function creates a table of counts for each unique item in the vector.as.data.frame
function for easier manipulation.min
function on the Freq
column of the data frame.Freq
column to the minimum count found in the previous step.print
function.vec <- c('apple', 'banana', 'apple', 'orange', 'banana', 'apple', 'kiwi')
# Step 2: Create a table of counts
count_table <- table(vec)
# Step 3: Convert the table to a data frame
count_df <- as.data.frame(count_table)
# Step 4: Find the minimum count
min_count <- min(count_df$Freq)
# Step 5: Subset the data frame to get the item(s) with the minimum count
min_items <- count_df[count_df$Freq == min_count, ]
# Step 6: Print the item(s) with the minimum occurrences
print(min_items)
vec Freq 4 kiwi 1 3 orange 1
In this example,
vec
containing several integer elements.table
function to count the occurrences of each integer in the vector. This function creates a table of counts for each unique item in the vector.as.data.frame
function for easier manipulation.min
function on the Freq
column of the data frame.Freq
column to the minimum count found in the previous step.print
function.vec <- c(1, 2, 3, 1, 2, 1, 4, 1, 5, 1)
# Step 2: Create a table of counts
count_table <- table(vec)
# Step 3: Convert the table to a data frame
count_df <- as.data.frame(count_table)
# Step 4: Find the minimum count
min_count <- min(count_df$Freq)
# Step 5: Subset the data frame to get the item(s) with the minimum count
min_items <- count_df[count_df$Freq == min_count, ]
# Step 6: Print the item(s) with the minimum occurrences
print(min_items)
vec Freq 3 3 1 4 4 1 5 5 1
In this tutorial, we learned How to find the Item with Minimum Number of Occurrences in a Vector in R language with well detailed examples.