How to separate first text value and the remaining text in an R vector?

R ProgrammingServer Side ProgrammingProgramming

To separate first text value and the remaining text in an R, we can follow the below steps −

  • First of all, create a vector.

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

Example

Create the vector

Let’s create a vector as shown below −

x<-sample(c("Data","Machine
Learning","Python","R","Java","SQL","Tableu"),25,replace=TRUE)
x

Output

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

[1] "Python"             "Python"           "Machine
Learning" [4] "Python"             "Java"   "Python" [7] "Java"               "SQL"     "R" [10] "Data"   "Tableu"   "Python" [13] "Machine
Learning" "R"       "Machine
Learning" [16] "Machine
Learning" "Java"             "Tableu" [19] "Data"              "Tableu"            "R" [22] "Java"              "Machine
Learning" "Python" [25] "Tableu"

Subset first value and rest of the text in string vector

Using str_split function from stringr package to subset first text value and the remaining text in each element of vector x −

x<-sample(c("Data","Machine
Learning","Python","R","Java","SQL","Tableu"),25,replace=TRUE)
library(stringr)
str_split(x,"(?<=.{1})",2)

Output

[[1]]
[1] "D" "ata"
[[2]]
[1] "T" "ableu"
[[3]]
[1] "M" "achine Learning"
[[4]]
[1] "J" "ava"
[[5]]
[1] "J" "ava"
[[6]]
[1] "P" "ython"
[[7]]
[1] "J" "ava"
[[8]]
[1] "M" "achine Learning"
[[9]]
[1] "R" ""
[[10]]
[1] "R" ""
[[11]]
[1] "R" ""
[[12]]
[1] "M" "achine Learning"
[[13]]
[1] "P" "ython"
[[14]]
[1] "T" "ableu"
[[15]]
[1] "M" "achine Learning"
[[16]]
[1] "J" "ava"
[[17]]
[1] "J" "ava"
[[18]]
[1] "D" "ata"
[[19]]
[1] "T" "ableu"
[[20]]
[1] "D" "ata"
[[21]]
[1] "T" "ableu"
[[22]]
[1] "T" "ableu"
[[23]]
[1] "T" "ableu"
[[24]]
[1] "T" "ableu"
[[25]]
[1] "T" "ableu"
raja
Updated on 11-Nov-2021 07:21:45

Advertisements