如何在 R 向量中分离第一个文本值和剩余文本?
要将第一个文本值和R中的剩余文本分开,我们可以按照以下步骤操作-
首先,创建一个向量。
然后,使用stringr包中的str_split函数将第一个文本值和剩余文本分开。
示例
创建向量
让我们创建一个如下所示的向量-
x<-sample(c("Data","Machine Learning","Python","R","Java","SQL","Tableu"),25,replace=TRUE) x输出结果
执行时,上述脚本生成以下内容output(thisoutputwillvaryonyoursystemduetorandomization)-
[1] "Python" "Python" "Machine\nLearning" [4] "Python" "Java" "Python" [7] "Java" "SQL" "R" [10] "Data" "Tableu" "Python" [13] "Machine\nLearning" "R" "Machine\nLearning" [16] "Machine\nLearning" "Java" "Tableu" [19] "Data" "Tableu" "R" [22] "Java" "Machine\nLearning" "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"