To find the index of a substring in R, you can use the `gregexpr` function.
In this example,
str <- "Hello World"
pattern <- "World"
result <- gregexpr(pattern, str, fixed = TRUE)
indices <- result[[1]]
print(indices[1])
[1] 7
In this example,
str
with a string value.gregexpr
function with the pattern "banana"
on str
to find the index of the substring.gregexpr
function returns a list of integer vectors indicating the start and end positions of the matches.str <- "apple banana apple cherry"
matches <- gregexpr("banana", str)
index <- matches[[1]][1]
print(paste("Index of substring is:", index))
Index of substring is: 7
In this tutorial, we learned How to find the Index of Substring in R language with well detailed examples.