How to separate first text value and the remaining text in R data frame column values?

R ProgrammingServer Side ProgrammingProgramming

To separate a first text value and the remaining text in R data frame column values, we can follow the below steps −

  • First of all, create a data frame.

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

Example

Create the data frame

Let’s create a data frame as shown below −

Names<-sample(c("India","Canada","Russia","USA","Belarus"),25,replace=TRUE)
df<-data.frame(Names)
df

Output

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

   Names
1  Russia
2  USA
3  India
4  USA
5  USA
6  India
7  Russia
8  Russia
9  Canada
10 Belarus
11 India
12 Belarus
13 USA
14 Russia
15 Canada
16 India
17 Russia
18 Russia
19 Russia
20 Belarus
21 India
22 India
23 Belarus
24 India
25 Russia

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 Names in data frame df −

Names-sample(c("India","Canada","Russia","USA","Belarus"),25,replace=TRUE)
df<-data.frame(Names)
library(stringr)
df$new<-str_split(df$Names,"(?<=.{1})",2)
df

Output

   Names      new
1  Russia R,  ussia
2  USA U,     SA
3  India I,   ndia
4  USA U,     SA
5  USA U,     SA
6  India I,   ndia
7  Russia R,  ussia
8  Russia R,  ussia
9  Canada C,  anada
10 Belarus B, elarus
11 India I,   ndia
12 Belarus B, elarus
13 USA U,     SA
14 Russia R,  ussia
15 Canada C,  anada
16 India I,   ndia
17 Russia R,  ussia
18 Russia R,  ussia
19 Russia R,  ussia
20 Belarus B, elarus
21 India I,   ndia
22 India I,   ndia
23 Belarus B, elarus
24 India I,   ndia
25 Russia R,  ussia
raja
Updated on 09-Nov-2021 06:55:19

Advertisements