To count the number of occurrences of a specific element in a vector in R, you can use the sum()
function with logical comparison.
In this example,
my_vector
with elements.sum()
function with a logical comparison to count the occurrences of a specific element.sum()
function then adds up the TRUE values, effectively counting the occurrences.my_vector <- c(1, 2, 3, 1, 4, 1, 5)
count <- sum(my_vector == 1)
print(paste("Count of 1 in the vector is:", count))
Count of 1 in the vector is: 3
In this example,
str_vector
with string elements.sum()
function with a logical comparison to count the occurrences of a specific string.sum()
function then adds up the TRUE values, effectively counting the occurrences.str_vector <- c("apple", "banana", "apple", "cherry", "apple")
count <- sum(str_vector == "apple")
print(paste("Count of 'apple' in the vector is:", count))
Count of 'apple' in the vector is: 3
In this tutorial, we learned How to count the Number of Occurrences of Specific Element in the List in R language with well detailed examples.