【问题标题】:How to split R data.frame column based regular expression condition如何拆分基于 R data.frame 列的正则表达式条件
【发布时间】:2014-12-10 14:27:45
【问题描述】:

我有一个data.frame,我想根据正则表达式将其中一列拆分为两列。更具体地说,字符串在括号中具有后缀,需要将其提取到自己的列中。

例如我想从这里出发:

dfInit <- data.frame(VAR = paste0(c(1:10),"(",c("A","B"),")"))

到这里:

dfFinal <- data.frame(VAR1 = c(1:10), VAR2 = c("A","B"))

【问题讨论】:

    标签: regex r dataframe


    【解决方案1】:

    1) gsubfn::read.pattern gsubfn 包中的read.pattern 可以做到这一点。与正则 r 表达式括号部分的匹配项被视为字段:

    library(gsubfn)
    read.pattern(text = as.character(dfInit$VAR), pattern = "(.*)[(](.*)[)]$")
    

    给予:

       V1 V2
    1   1  A
    2   2  B
    3   3  A
    4   4  B
    5   5  A
    6   6  B
    7   7  A
    8   8  B
    9   9  A
    10 10  B
    

    2) sub 另一种方式是使用sub

    data.frame(V1=sub("\\(.*", "", dfInit$VAR), V2=sub(".*\\((.)\\)$", "\\1", dfInit$VAR))
    

    给出相同的结果。

    3) read.table 此解决方案不使用正则表达式:

    read.table(text = as.character(dfInit$VAR), sep = "(", comment = ")")
    

    给出相同的结果。

    【讨论】:

      【解决方案2】:

      你也可以使用tidyr中的extract

      library(tidyr)
      extract(dfInit, VAR, c("VAR1", "VAR2"), "(\\d+).([[:alpha:]]+).", convert=TRUE) # edited and added `convert=TRUE` as per @aosmith's comments.
      
      
      
      #    VAR1 VAR2
      #1     1    A
      #2     2    B
      #3     3    A
      #4     4    B
      #5     5    A
      #6     6    B
      #7     7    A
      #8     8    B
      #9     9    A
      #10   10    B
      

      【讨论】:

      • extract 中将convert 设置为TRUE 避免了mutate 的需要,尽管VAR2 然后被转换为一个因子。
      【解决方案3】:

      Split column at delimiter in data frame

      dfFinal <- within(dfInit, VAR<-data.frame(do.call('rbind', strsplit(as.character(VAR), '[[:punct:]]'))))
      
      > dfFinal
         VAR.X1 VAR.X2
      1       1      A
      2       2      B
      3       3      A
      4       4      B
      5       5      A
      6       6      B
      7       7      A
      8       8      B
      9       9      A
      10     10      B
      

      【讨论】:

        【解决方案4】:

        regmatchesgregexpr 的方法:

        as.data.frame(do.call(rbind, regmatches(dfInit$VAR, gregexpr("\\w+", dfInit$VAR))))
        

        【讨论】:

          【解决方案5】:

          您也可以使用splitstackshape 中的cSplit

          library(splitstackshape)
          cSplit(dfInit, "VAR", "[()]", fixed=FALSE)
          #    VAR_1 VAR_2
          # 1:     1     A
          # 2:     2     B
          # 3:     3     A
          # 4:     4     B
          # 5:     5     A
          # 6:     6     B
          # 7:     7     A
          # 8:     8     B
          # 9:     9     A
          #10:    10     B
          

          【讨论】:

          • @akrun - 非常感谢您的编辑。我不认为正则表达式 sep 是可能的。
          • 没问题。我之前也遇到过类似的情况,Ananda Mahto 提出了这个建议。
          猜你喜欢
          • 2020-02-07
          • 1970-01-01
          • 2021-08-26
          • 2010-10-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多