根据R中的模式拆分字符串

split a string according to pattern in R

我有一个字符串列表如下:

a <- c("aaaa 12 comments","bb cc 124 dd 134 commments","hh tt hhh 17 comments")

我想创建两个向量,一个只包含文本,一个只包含评论数。

评论的数量可以不同,但​​总是列在最后。

想要的结果:

a1 <- c("aaaa","bb cc 124 dd","hh tt hhh")
a2 <- c("12 comments","134 commments","17 comments")

非常感谢任何帮助。我正在尝试使用 gsub,但它不起作用:

> gsub('[:digit:]*[:space:]comments$','', a)
[1] "aaaa 12 comments"           "bb cc 124 dd 134 commments" "hh tt hhh 17 comments"  

使用

a1 <- gsub('([0-9]+ comments$)',"", a)
library(stringr)
a2 <- unlist(str_extract_all(a,'([0-9]+ comments$)'))