- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
- Related Articles
- How to extract number from string if string is in different format than normal in R data frame?
- How to extract only factor columns name from an R data frame?
- How to extract the factor levels from factor column in an R data frame?
- How to extract the last row from list of a data frame in R?
- How to extract the first digit from a character column in an R data frame?
- How to extract a single column of an R data frame as a data frame?
- How to extract data frame columns stored in a list in R?
- Extract columns with a string in column name of an R data frame.
- Extract a particular level from factor column in an R data frame.
- How to extract unique combination of rows in an R data frame?
- How to extract a particular value based on index from an R data frame column?
- How to extract characters from a string in R?
- How to remove single quote from string column in an R data frame?
- How to extract columns of a data frame in R using dplyr package?
- How to extract words from a string vector in R?

Advertisements