【问题标题】:splitting filename text by underscores using R使用 R 用下划线分割文件名文本
【发布时间】:2014-04-22 19:47:47
【问题描述】:

在 R 中,我想采用以下格式的文件名集合,并返回第二个下划线右侧的数字(这将始终是一个数字)和第三个下划线右侧的文本字符串(这将是字母和数字的组合)。

我有这种格式的文件名:

HELP_PLEASE_4_ME

我要提取号码4和文字ME

然后我想在我的数据框中创建一个新字段,用于存储这两种类型的数据。有什么建议吗?

【问题讨论】:

  • 试试 strsplit('HELP_PLEASE_4_ME', '_') 或等待一些正则表达式专家发布答案。

标签: r text split filenames


【解决方案1】:

这是一个使用regexecregmatches 提取模式的选项:

matches <- regmatches(df$a, regexec("^.*?_.*?_([0-9]+)_([[:alnum:]]+)$", df$a))
df[c("match.1", "match.2")] <- t(sapply(matches, `[`, -1)) # first result for each match is full regular expression so need to drop that.

生产:

                 a match.1 match.2
1 HELP_PLEASE_4_ME       4      ME
2  SOS_WOW_3_Y34OU       3   Y34OU

如果任何行没有预期的结构,这将中断,但我认为这是您想要发生的(即提醒您的数据不是您认为的那样)。基于strsplit 的方法需要额外检查以确保您的数据与您认为的一样。

还有数据:

df <- data.frame(a=c("HELP_PLEASE_4_ME", "SOS_WOW_3_Y34OU"), stringsAsFactors=F)

【讨论】:

    【解决方案2】:

    @BrodieG 的强制性 stringr 版本非常漂亮的答案:

    df[c("match.1", "match.2")] <- 
      t(sapply(str_match_all(df$a, "^.*?_.*?_([0-9]+)_([[:alnum:]]+)$"), "[", 2:3))
    

    仅用于上下文。您应该接受 BrodieG 的回答。

    【讨论】:

      【解决方案3】:

      由于您已经知道需要第二个和第三个下划线之后的文本,您可以使用strsplit 并获取第三个和第四个结果。

      > x <- "HELP_PLEASE_4_ME"
      > spl <- unlist(strsplit(x, "_"))[3:4]
      > data.frame(string = x, under2 = spl[1], under3 = spl[2])
      ##             string under2 under3
      ## 1 HELP_PLEASE_4_ME      4     ME
      

      然后,对于更长的向量,您可以在此处执行最后两行之类的操作。

      ## set up some data
      > word1 <- c("HELLO", "GOODBYE", "HI", "BYE")
      > word2 <- c("ONE", "TWO", "THREE", "FOUR")
      > nums <- 20:23
      > word3 <- c("ME", "YOU", "THEM", "US")
      > XX <-paste0(word1, "_", word2, "_", nums, "_", word3)
      > XX
      ## [1] "HELLO_ONE_20_ME"    "GOODBYE_TWO_21_YOU" 
      ## [3] "HI_THREE_22_THEM"   "BYE_FOUR_23_US"    
      ## ------------------------------------------------
      ## process it
      > spl <- do.call(rbind, strsplit(XX, "_"))[, 3:4]
      > data.frame(cbind(XX, spl))
      ##                   XX V2   V3
      ## 1    HELLO_ONE_20_ME 20   ME
      ## 2 GOODBYE_TWO_21_YOU 21  YOU
      ## 3   HI_THREE_22_THEM 22 THEM
      ## 4     BYE_FOUR_23_US 23   US
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-04-06
        • 2015-04-19
        • 2013-11-09
        • 1970-01-01
        • 2011-11-10
        • 1970-01-01
        • 1970-01-01
        • 2012-02-10
        相关资源
        最近更新 更多