Extract Substring from a String in R

Learn to extract Substring from a String in R programming language using substring() function.

The syntax of R substring function is

substring(c, first, last)

where :

  • c is the string
  • first is the starting position of substring (in the main string) to be extracted
  • last is the ending position of substring (in the main string) to be extracted. last is optional, in which case last is taken as whole length of the string.

Example 1 – Get Substring from a String in R

In this example, we will take a string, and find its substring given first and last positions.

r_strings_substring.R

# Example R program to find substring

str = 'Hello World! Welcome to learning R programming language'

#substring(c, first, last)
subStr = substring(str, 13, 23)

print (subStr)

Output

$ Rscript r_strings_substring.R 
[1] " Welcome to"
ADVERTISEMENT

Example 2 – Get Substring from a String in R – Without “last”

In this example, we will take a string, and find its substring given only first position. If last position is given, end of the string is considered as last.

r_strings_substring.R

# Example R program to find substring

str = 'Hello World! Welcome to learning R programming language'

#substring(c, first, last=nchar(c))
subStr = substring(str, 13)

print (subStr)

Output

$ Rscript r_strings_substring.R 
[1] " Welcome to learning R programming language"

Conclusion

In this R Tutorial, we have learnt to find Substring from a String in R programming language using substring() function.