【问题标题】:Split columns by number in a dataframe在数据框中按数字拆分列
【发布时间】:2017-05-09 12:21:04
【问题描述】:

我试图在一个相当凌乱的数据框中分离一列。

section
View 500
V458
453

我想以此创建一个新列。使用如下所示的首选输出。

section  section numbers  
View     500
V        458
         453

我一直在尝试研究它,但我有时间研究它。我可以在第一行的情况下将它们分开,因为我可以像这样使用正则表达式。

df_split <- separate(df, col = section, into = c("section", "section_number"), sep = " +[1-9]")

但我似乎找不到使用“或”类型语句的方法。如果有人有任何意见,那就太好了。

【问题讨论】:

  • "\\s*(?=\\d)" PCRE 正则表达式可能会有所帮助。
  • 似乎对我不起作用。
  • 我的意思是do.call(rbind, str_split(df$section, '\\s*(?=\\d)', 2))

标签: r regex dataframe split


【解决方案1】:

这是一个使用base Rread.csvsub 的选项。我们将末尾的数字捕获为一个组 ((\\d+)$),并在 sub 中用逗号和组的反向引用 (\\1) 替换,然后用 read.csv 读取它

read.csv(text=sub("\\s*(\\d+)$", ",\\1", df1$section), fill=TRUE, header=FALSE, 
         col.names = c("section", "section number"), stringsAsFactors=FALSE)
#   section section.number
#1    View            500
#2       V            458
#3                    453

【讨论】:

    【解决方案2】:

    使用stringr(假设原始df只有一列名为section):

    library(stringr)
    df_split <- as.data.frame(str_match(df$section, "([A-Za-z]*)\\s*([0-9]*)")[,2:3])
    names(df_split) <- c('section', 'section numbers')
    df_split
    
    #  section section numbers
    #1    View             500
    #2       V             458
    #3                     453
    

    【讨论】:

      【解决方案3】:

      您可以为此使用tidyr

      tidyr::extract(df,section, c("section", "section number"), 
                     regex="([[:alpha:]]*)[[:space:]]*([[:digit:]]*)")
        section section number
      1    View            500
      2       V            458
      3                    453
      

      【讨论】:

        【解决方案4】:

        使用简单的gsub 对我来说是一个选择:

        section <- c('View 500', 'V458', '453')
        
        cbind(section = trimws(gsub('[0-9]', '', section)), 
              section_numbers = trimws(gsub('[a-zA-Z]', '', section)))
        

        我使用trimws 来删除任何不需要的空格。

        输出:

            section section_numbers
        [1,] "View"  "500"          
        [2,] "V"     "458"          
        [3,] ""      "453" 
        

        【讨论】:

          【解决方案5】:

          您可以使用extract,它也来自tidyr 包,您可以使用它指定捕获组,在此处将它们设为可选,并且可以非常灵活地处理不同的情况:

          library(tidyr)
          df %>% extract(section, into = c("alpha", "numeric"), regex = "([a-zA-Z]+)?\\s?(\\d+)?")
          
          #  alpha numeric
          #1  View     500
          #2     V     458
          #3  <NA>     453
          

          【讨论】:

            猜你喜欢
            • 2016-06-27
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-01-18
            • 1970-01-01
            • 2011-10-26
            相关资源
            最近更新 更多