Open In App

How to find SubString in R programming?

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to see how to find substring in R programming language. 

R provides different ways to find substrings. These are:

  • Using substr() method
  • Using str_detect() method
  • Using grep() method

Method 1: Using substr() method

Find substring in R using substr() method in R Programming is used to find the sub-string from starting index to the ending index values in a string.

Syntax: substr(string_name, start, end)

Return: Returns the sub string from a given string using indexes. 

Example 1:

R




# Given String
gfg < - "Geeks For Geeks"
  
# Using substr() method
answer < - substr(gfg, 0, 5)
  
print(answer)


Output:

[1] "Geeks"

Example 2:

R




# Given String
gfg < - "The quick brown fox jumps over the lazy dog"
  
# Using substr() method
answer < - substr(gfg, 20, 30)
  
print(answer)


Output:
 

[1] " jumps over"

Method 2: Using str_detect() method

str_detect() Function in R Language is used to check if the specified match of the substring exists in the original string. It will return TRUE for a match found otherwise FALSE against each of the elements of the Vector or matrix.

Syntax: str_detect(string, pattern)

Parameter:

  • string: specified string
  • pattern: Pattern to be matched

Example:

R




# R Program to illustrate
# the use of str_detect function
  
# Loading library
library(stringr)
  
# Creating vector
x <- c("Geeks", "Hello", "Welcome", "For")
  
# Pattern to be matched
pat <- "Geeks"
  
# Calling str_detect() function
str_detect(x, pat)


Output:

[1]  TRUE FALSE FALSE FALSE

Method 3: Using grep() method

grep() function returns the index at which the pattern is found in the vector. If there are multiple occurrences of the pattern, it returns a list of indices of the occurrences. This is very useful as it not only tells us about the occurrence of the pattern but also of its location in the vector.

Syntax: grep(pattern, string, ignore.case=FALSE)

Parameters:

  • pattern: A regular expressions pattern.
  • string: The character vector to be searched.
  • ignore.case: Whether to ignore case in the search. Here ignore.case is an optional parameter as is set to FALSE by default.

Example:

R




str <- c("Hello", "hello", "hi", "hey")
grep('he', str)


Output:

[1] 2 4


Last Updated : 21 Oct, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads