R 仅使用分隔符中的最后一个分隔符拆分字符串

R 仅使用分隔符中的最后一个分隔符拆分字符串,r,R,我有一个字符变量,我希望根据“-”分隔符将其拆分为两个变量,但是,我只希望根据最后一个分隔符拆分,因为字符串中可能有多个“-”。例如: Input Output1 Output2 foo - bar foo bar hey-now-man hey-now man say-now-girl say-now girl fine-now fine now 我尝试过使用strsplit,但没有效果。您可以尝试使用gregexpr

我有一个字符变量,我希望根据“-”分隔符将其拆分为两个变量,但是,我只希望根据最后一个分隔符拆分,因为字符串中可能有多个“-”。例如:

Input          Output1  Output2
foo - bar      foo      bar
hey-now-man    hey-now  man
say-now-girl   say-now  girl
fine-now       fine     now

我尝试过使用strsplit,但没有效果。

您可以尝试使用
gregexpr

a=c("foo - bar","hey-now-man","say-now-girl","fine-now")
lastdelim = tail(gregexpr("-",a)[[1]],n=1)
output1 = sapply(a,function(x) {substr(x,1,lastdelim-1)})
output2 = sapply(a,function(x) {substr(x,lastdelim+1,nchar(x))})

基于
stringi
数据的解决方案。表
:反转字符串并将其拆分为固定项,然后反转回:

library(stringi)
x <- c('foo - bar', 'hey-now-man', 'say-now-girl', 'fine-now')

lapply(stri_split_regex(stri_reverse(x), pattern = '[-\\s]+', n = 2), stri_reverse)

您还可以使用负前瞻:

df <- tibble(input = c("foo - bar", "hey-now-man", "say-now-girl", "fine-now"))

df %>% 
    separate(input, into = c("output1", "output2"), sep = "\\-(?!.*-)", remove = FALSE)
df%
分离(输入,输入=c(“输出1”,“输出2”),sep=“\\-(?!.-”),删除=FALSE)
参考文献:

[1]

[2]

使用unglue可以执行以下操作:

#安装程序包(“unglue”)
图书馆(非蓝色)
测向输入输出1输出2
#>1富吧富吧
#>嘿,伙计,嘿,伙计
#>现在说女孩现在说女孩
#>现在好了现在好了

由(v0.3.0)创建于2019-11-06,在尝试运行时收到一些错误:lastdelim=tail(gregexpr(“-”,x)[[1]],n=1)gregexpr(“-”,x)中的错误:对象“x”未找到我的错误,
x
应该是
a
(我在途中更改了名称,没有到处更新)
df <- tibble(input = c("foo - bar", "hey-now-man", "say-now-girl", "fine-now"))

df %>% 
    separate(input, into = c("output1", "output2"), sep = "\\-(?!.*-)", remove = FALSE)