To find the indices of all occurrences of a substring in R, you can use the regexpr and gregexpr functions to find all occurrences and store their indices.
In this example,
str
with a string value.gregexpr
function with a regular expression pattern to find all occurrences of the pattern within str
and store their indices.str <- 'Hello Hello Hello'
indices <- gregexpr('Hello', str)[[1]]
print(paste('Indices of all occurrences:', indices))
Indices of all occurrences: 1 7 13
In this example,
str1
and str2
with different values.gregexpr
function with a regular expression pattern to find all occurrences of the pattern within str1
and store their indices.str1 <- 'apple banana cherry banana'
str2 <- 'banana'
indices <- gregexpr(str2, str1)[[1]]
print(paste('Indices of all occurrences:', indices))
Indices of all occurrences: 7 21
In this tutorial, we learned How to find the Indices of All Occurrences of Substring in R language with well detailed examples.