按R中的最后一个空格分割字符串
问题描述:
我有一个向量,其中包含多个空格的字符串.我想将其拆分为两个向量,最后一个空格将其拆分.例如:
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')
应该成为
vec1 = c('This is', 'And', 'And one more again')
vec2 = c('one', 'another', 'again')
是否有一种快速简便的方法来做到这一点?在使用gsub和regex之前,我已经做过类似的事情,并设法使用以下命令获取第二个向量
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)
但是无法弄清楚如何获得vec1.
But can't work out how to get vec1.
预先感谢
答
以下是使用超前断言的一种方法:
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"