How to extract number from string in R data frame?


To extract number from string in R data frame, we can follow the below steps −

  • First of all, create a data frame.

  • Then, use gsub function to extract number from string.

Example

Create the data frame

Let’s create a data frame as shown below −

x<-
sample(c("grp12","grp01","grp05","grp03","grp04","grp09","grp10","grp11","grp02","grp06","grp07","grp08"),25,replace=TRUE)
df<-data.frame(x)
df

Output

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

    x
1  grp01
2  grp04
3  grp08
4  grp01
5  grp12
6  grp08
7  grp08
8  grp09
9  grp02
10 grp12
11 grp05
12 grp10
13 grp04
14 grp06
15 grp03
16 grp08
17 grp06
18 grp05
19 grp10
20 grp10
21 grp06
22 grp04
23 grp04
24 grp06
25 grp06

Extract number from string

Using gsub function to extract number from string column x in data frame df −

x<-
sample(c("grp12","grp01","grp05","grp03","grp04","grp09","grp10","grp11","grp02","grp06","grp07","grp08"),25,replace=TRUE)
df<-data.frame(x)
df$Group<-gsub("[^0-9]","",df$x)
df

Output

     x  Group
1  grp01 01
2  grp04 04
3  grp08 08
4  grp01 01
5  grp12 12
6  grp08 08
7  grp08 08
8  grp09 09
9  grp02 02
10 grp12 12
11 grp05 05
12 grp10 10
13 grp04 04
14 grp06 06
15 grp03 03
16 grp08 08
17 grp06 06
18 grp05 05
19 grp10 10
20 grp10 10
21 grp06 06
22 grp04 04
23 grp04 04
24 grp06 06
25 grp06 06

Updated on: 11-Nov-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements