问题
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