R Identify & Count Exact Matches of Pattern in String (2 Examples)
In this R tutorial you’ll learn how to identify the index position and how to count exact matches in character strings.
Creation of Example Data
x <- c("abc", "abc_1", "abc", "abc_2", "abc") # Example vector in R x # Show example vector in RStudio console # [1] "abc" "abc_1" "abc" "abc_2" "abc" |
x <- c("abc", "abc_1", "abc", "abc_2", "abc") # Example vector in R x # Show example vector in RStudio console # [1] "abc" "abc_1" "abc" "abc_2" "abc"
Example 1: Get Exact Match Positions of Pattern in Character String Vector
which(x == "abc") # Find index positions # [1] 1 3 5 |
which(x == "abc") # Find index positions # [1] 1 3 5
Example 2: Count Exact Matches of Pattern in Character String Vector
sum(x == "abc") # Count occurrences # [1] 3 |
sum(x == "abc") # Count occurrences # [1] 3
Further Resources & Related Tutorials
Have a look at the following tutorials. They focus on topics such as character strings, vectors, numeric values, and extracting data.