按R中的最后一个空格拆分字符串

时间:2022-08-22 12:45:57

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

有没有快速简便的方法来做到这一点?我在使用gsub和regex之前做过类似的事情,并且设法使用以下内容获得第二个向量

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

But can't work out how to get vec1.

但无法弄清楚如何获得vec1。

Thanks in advance

提前致谢

1 个解决方案

#1


6  

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" 

#1


6  

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"