To count the number of occurrences of a specific item in a vector in R, you can use the sum
function along with logical indexing.
In this example,
vec
with a set of numerical values.item
that holds the value we want to count in the vector.sum
function combined with logical indexing to count the occurrences of item
in vec
. The logical indexing vec == item
creates a logical vector where each element is TRUE
if it matches item
and FALSE
otherwise.sum
function then adds up the TRUE
values, treating them as 1 and FALSE
values as 0, resulting in the count of occurrences of item
in vec
.print
function.vec <- c(1, 2, 3, 2, 2, 4, 5, 2)
item <- 2
count <- sum(vec == item)
print(count)
4
In this example,
char_vec
with a set of string values.str_item
that holds the string we want to count in the vector.sum
function combined with logical indexing to count the occurrences of str_item
in char_vec
. The logical indexing char_vec == str_item
creates a logical vector where each element is TRUE
if it matches str_item
and FALSE
otherwise.sum
function then adds up the TRUE
values, treating them as 1 and FALSE
values as 0, resulting in the count of occurrences of str_item
in char_vec
.print
function.char_vec <- c("apple", "banana", "apple", "cherry", "banana", "apple")
str_item <- "apple"
count <- sum(char_vec == str_item)
print(count)
3
In this example,
log_vec
with a set of logical values TRUE
and FALSE
.log_item
that holds the logical value we want to count in the vector.sum
function directly on the logical vector log_vec
where each TRUE
value is treated as 1 and each FALSE
value as 0. This effectively counts the number of TRUE
values in log_vec
.FALSE
values, we can use the logical negation operator !
to flip the values in log_vec
and then use the sum
function.print
function.log_vec <- c(TRUE, FALSE, TRUE, TRUE, FALSE, TRUE, FALSE)
log_item <- TRUE
count <- sum(log_vec == log_item)
print(count)
4
In this tutorial, we learned How to count the Number of Occurrences of Specific Item in the Vector in R language with well detailed examples.