如何在 R 向量中分离第一个文本值和剩下的文本值?


要分离 R 中的第一个文本值和其余文本值,我们可以按照以下步骤进行 −

  • 首先,创建一个向量。

  • 然后,使用来自 stringr 包的 str_split 函数分离第一个文本值和其余文本值。

示例

创建向量

让我们创建一个如下所示的向量 −

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

输出

执行上述脚本后,将生成以下输出(此输出因随机性而异) −

[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"

提取字符串向量中的第一个值和其余文本

使用 stringr 包的 str_split 函数提取向量 x 中每个元素的第一个文本值和其余文本 −

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

输出

[[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"

更新日期:11-Nov-2021

75 次观看

开启您的 事业

通过完成课程获得认证

开始
广告