Split string by final space in R

允我心安 提交于 2019-12-19 03:57:01

问题


I have a vector a strings with a number of spaces in. I would like to split this into two vectors split by the final space. For example:

vec <- c('This is one', 'And another', 'And one more again')

Should become

vec1 = c('This is', 'And', 'And one more again')
vec2 = c('one', 'another', 'again')

Is there a quick and easy way to do this? I have done similar things before using gsub and regex, and have managed to get the second vector using the following

vec2 <- gsub(".* ", "", vec)

But can't work out how to get vec1.

Thanks in advance


回答1:


Here is one way using a lookahead assertion:

do.call(rbind, strsplit(vec, ' (?=[^ ]+$)', perl=TRUE))
#      [,1]           [,2]     
# [1,] "This is"      "one"    
# [2,] "And"          "another"
# [3,] "And one more" "again" 


来源:https://stackoverflow.com/questions/19959697/split-string-by-final-space-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!