How to separate a specific text and the remaining text in data.table object column in R?


To separate a specific text and the remaining text in data.table object column in R, we can follow the below steps −

  • First of all, create a data.table object.

  • Then, use str_split function from stringr package to separate first text value and the remaining text.

Example

Create the data.table object

Let’s create a data.table object as shown below −

library(data.table)
Student_ID<-
sample(c("1Rosy","3Numan","8John","2Shera","9Hina"),25,replace=TRUE)
DT<-data.table(Student_ID)
DT

Output

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

   Student_ID
1:  9Hina
2:  1Rosy
3:  3Numan
4:  9Hina
5:  8John
6:  9Hina
7:  9Hina
8:  1Rosy
9:  3Numan
10: 8John
11: 9Hina
12: 1Rosy
13: 9Hina
14: 8John
15: 1Rosy
16: 2Shera
17: 1Rosy
18: 3Numan
19: 8John
20: 1Rosy
21: 9Hina
22: 8John
23: 8John
24: 8John
25: 9Hina
Student_ID

Separate first value and rest of the text in string column

Using str_split function from stringr package to separate first text value and the remaining text in each row of column Student_ID in data.table object DT −

library(data.table)
Student_ID<-
sample(c("1Rosy","3Numan","8John","2Shera","9Hina"),25,replace=TRUE)
DT<-data.table(Student_ID)
library(stringr)
DT$ID_Name<-str_split(DT$Student_ID,"(?<=.{1})",2)
DT

Output

   Student_ID ID_Name
1:  9Hina 9,   Hina
2:  1Rosy 1,   Rosy
3:  3Numan 3,  Numan
4:  9Hina 9,   Hina
5:  8John 8,   John
6:  9Hina 9,   Hina
7:  9Hina 9,   Hina
8:  1Rosy 1,   Rosy
9:  3Numan 3,  Numan
10: 8John 8,   John
11: 9Hina 9,   Hina
12: 1Rosy 1,   Rosy
13: 9Hina 9,   Hina
14: 8John 8,   John
15: 1Rosy 1,   Rosy
16: 2Shera 2,  Shera
17: 1Rosy 1,   Rosy
18: 3Numan 3  ,Numan
19: 8John 8,   John
20: 1Rosy 1,   Rosy
21: 9Hina 9,   Hina
22: 8John 8,   John
23: 8John 8,   John
24: 8John 8,   John
25: 9Hina 9,   Hina
Student_ID    ID_Name

Updated on: 15-Nov-2021

112 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements