【问题标题】:Split Character String Using Only Last Delimiter in r仅使用 r 中的最后一个分隔符拆分字符串
【发布时间】:2017-05-19 15:22:00
【问题描述】:

我有一个字符变量,我想根据“-”分隔符将其拆分为 2 个变量,但是,我只想根据最后一个分隔符进行拆分,因为字符串中可能有多个“-”。示例:

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

我尝试过使用 strsplit 无济于事。

【问题讨论】:

    标签: r


    【解决方案1】:

    基于stringidata.table的解决方案:将字符串反转,拆分成固定项,再反转回来:

    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)
    

    如果我们想用这个创建data.frame

    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
    

    【讨论】:

      【解决方案2】:

      您可以尝试使用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))})
      

      【讨论】:

      • 尝试运行时收到一些错误:lastdelim = tail(gregexpr("-",x)[[1]],n=1) gregexpr("-", x) 中的错误:找不到对象“x”
      • 我的错,x 应该是a(我在途中更改了名称,并没有到处更新)
      【解决方案3】:

      使用 脱胶 你会这样做:

      # install.packages("unglue")
      library(unglue)
      df <- data.frame(input = c("foo - bar","hey-now-man","say-now-girl","fine-now"))
      unglue_unnest(df, input, "{output1}{=\\s*-\\s*}{output2=[^-]+}", remove = FALSE)
      #>          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
      

      reprex package (v0.3.0) 于 2019 年 11 月 6 日创建

      【讨论】:

        【解决方案4】:

        您也可以使用否定前瞻:

        df <- tibble(input = c("foo - bar", "hey-now-man", "say-now-girl", "fine-now"))
        
        df %>% 
            separate(input, into = c("output1", "output2"), sep = "\\-(?!.*-)", remove = FALSE)
        

        参考:

        [1]https://frightanic.com/software-development/regex-match-last-occurrence/

        [2]https://www.regular-expressions.info/lookaround.html

        【讨论】:

          猜你喜欢
          • 2017-04-23
          • 1970-01-01
          • 1970-01-01
          • 2013-02-07
          • 1970-01-01
          • 2016-09-15
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多