Split Character String Using Only Last Delimiter in r

后端 未结 4 909
暖寄归人
暖寄归人 2021-01-16 07:38

I have a character variable that I would like to split into 2 variables based on a \"-\" delimiter, however, I would only like to split based on the last delimiter as there

4条回答
  •  春和景丽
    2021-01-16 08:06

    A solution based on stringi and data.table: reverse the string and split it into fixed items and then reverse back:

    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)
    

    If we want to make a data.frame with this:

    y <- lapply(stri_split_regex(stri_reverse(x), pattern = '[-\\s]+', n = 2), stri_reverse)
    
    y <- setNames(data.table::transpose(y)[2:1], c('output1', 'output2'))
    
    df <- as.data.frame(c(list(input = x), y))
    
    # > df
    # input output1 output2
    # 1    foo - bar     foo     bar
    # 2  hey-now-man hey-now     man
    # 3 say-now-girl say-now    girl
    # 4     fine-now    fine     now
    

提交回复
热议问题