Substring() function in R is widely used to either extract the characters present in the data or to manipulate the data. You can easily extract the required characters from a string and also replace the values in a string.

Hello folks, hope you are doing good. Today let’s focus on the substing function in R.

Table of Contents[

hide

]

The substring() Function Syntax

**Substring: **We can perform multiple things like extracting of values, replacement of values and more. For this we use functions like substr() and substring().

1

2

substr``(x,start,stop)

substring``(x,first,last=1000000L)

Where:

  • x = the input data / file.
  • Start / First= starting index of the substring.
  • **Stop / Last= **Ending index of the substring.

Extract characters using substring() function in R

Well, I hope that you are pretty much clear about the syntax. Now, let’s extract some characters from the string using our substring() function in R.

1

2

3

#returns the characters from 1,11

df<-(``"Journal_dev_private_limited"``)

substring``(df,1,11)

Output = “Journal_dev”

1

2

3

#returns the characters from 1-7

df<-(``"Journal_dev"``)

substring``(df,1,7)

Output = “Journal”

Congratulations, you just extracted the data from the given string. As you can observe, the substring() function in R takes the start/first and last/end values as arguments and indexes the string and returns a required substring of mentioned dimensions.


Replace using substring() function in R

With the help of substring() function, you can also replace the values in the string with your desired values. Seems to be interesting right? Then Let’s see how it works.

1

2

3

4

#returns the string by replacing the _ by space

df<-(``"We are_developers"``)

substring``(df,7,7)=``" "

df

Output = “We are developers”

1

2

3

4

#string replacement

df<-(``"R=is a language made for statistical analysis"``)

substring``(df,2,2)=``" "

df

Output = “R is a language made for statistical analysis”

Great, you did it! In this way, you can replace the values in a string with your desired value.

In the above case, you have replaced the ‘_’ (underscore) **and “=” (equal sign) with a ” ” (space). **I hope you got it better.


String replacement using substring() function

Till now, everything is good! But what if you are required to replace some values, which should reflect in all the strings present?

Don’t worry! We can replace the values and can make them to reflect on all the strings present.

Let’s see how it works!

1

2

3

4

#replaces the 4th letter of each string by $

df<-``c``(``"Alok"``,``"Joseph"``,``"Hayato"``,``"Kelly"``,``"Paloma"``,``"Moca"``)

substring``(df,4,4)<-``c``(``"$"``)

df

#r programming #function

The substring() function in R - Things to know
1.30 GEEK