如何提取R中的拆分字符串元素?
要拆分字符串向量元素,我们可以使用strsplit函数。如果我们想在拆分后提取字符串元素,则将使用双方括号和单方括号。双方括号提取字符串向量元素,单方括号提取分割后的元素。查看示例以了解其工作原理。
示例1
> x1<-c("Nhooo is an E-learning platform","E-learning is important","It helps in learning and growing at a faster rate") > x1输出结果
[1] "Nhooo is an E-learning platform" [2] "E-learning is important" [3] "It helps in learning and growing at a faster rate"
示例
> x1<-strsplit(x1," ") > x1输出结果
[[1]] [1] "Nhooo" "is" "an" "E-learning" [5] "platform" [[2]] [1] "E-learning" "is" "important" [[3]] [1] "It" "helps" "in" "learning" "and" "growing" [7] "at" "a" "faster" "rate"
示例
> x1[[1]][1] [1] "Nhooo" > x1[[1]][4] [1] "E-learning" > x1[[2]][1] [1] "E-learning" > x1[[3]][1] [1] "It" > x1[[3]][4] [1] "learning" > x1[[3]][8] [1] "a"
例2
> x2<-c("The purpose of our lives is to be happy","Difficult roads often lead to beautiful destinations","Sometimes the heart sees what is invisible to the eye","Life is beautiful","God is the greatest","Don't let yesterday take up too much today","Clarity is very important","Satisfaction defines the success","My life is my message","The best is yet to come","Life is a journey not a race","Life is short and the world is wide","Time is free but it's priceless","Your dream does not have an expiration date") > x2输出结果
[1] "The purpose of our lives is to be happy" [2] "Difficult roads often lead to beautiful destinations" [3] "Sometimes the heart sees what is invisible to the eye" [4] "Life is beautiful" [5] "God is the greatest" [6] "Don't let yesterday take up too much today" [7] "Clarity is very important" [8] "Satisfaction defines the success" [9] "My life is my message" [10] "The best is yet to come" [11] "Life is a journey not a race" [12] "Life is short and the world is wide" [13] "Time is free but it's priceless" [14] "Your dream does not have an expiration date"
示例
> x2<-strsplit(x2," ") > x2输出结果
[[1]] [1] "The" "purpose" "of" "our" "lives" "is" "to" [8] "be" "happy" [[2]] [1] "Difficult" "roads" "often" "lead" "to" [6] "beautiful" "destinations" [[3]] [1] "Sometimes" "the" "heart" "sees" "what" "is" [7] "invisible" "to" "the" "eye" [[4]] [1] "Life" "is" "beautiful" [[5]] [1] "God" "is" "the" "greatest" [[6]] [1] "Don't" "let" "yesterday" "take" "up" "too" [7] "much" "today" [[7]] [1] "Clarity" "is" "very" "important" [[8]] [1] "Satisfaction" "defines" "the" "success" [[9]] [1] "My" "life" "is" "my" "message" [[10]] [1] "The" "best" "is" "yet" "to" "come" [[11]] [1] "Life" "is" "a" "journey" "not" "a" "race" [[12]] [1] "Life" "is" "short" "and" "the" "world" "is" "wide" [[13]] [1] "Time" "is" "free" "but" "it's" "priceless" [[14]] [1] "Your" "dream" "does" "not" "have" [6] "an" "expiration" "date"
示例
> x2[[1]][1] > x2[[1]][2] > x2[[3]][1] > x2[[10]][2] > x2[[12]][1] > x2[[10]][1] > x2[[14]][2]输出结果
[1] "The" [1] "purpose" [1] "Sometimes" [1] "best" [1] "Life" [1] "The" [1] "dream"