【问题标题】:use gsub in R to cut the character out between two slashes在 R 中使用 gsub 在两个斜杠之间剪切字符
【发布时间】:2011-09-28 10:31:24
【问题描述】:

我有一个由 R 捕获的文件名,如下所示:

"0097_abcdef/0097_0/0097_0_04_bed.dbf"

我需要在两个斜线/(即0097_0)之间选择术语,但我尝试过gsub(".*/","",dbf.files[1]),但它给了我"0097_0_04_bed.dbf",这不是我想要的。

有人可以帮忙吗?谢谢。

【问题讨论】:

    标签: regex r


    【解决方案1】:

    你可以尝试使用 -

     .*/(.*)/.* 
    

    并使用第一组,例如\1

    > x = "0097_abcdef/0097_0/0097_0_04_bed.dbf"
    > sub(".*/(.*)/.*","\\1",x)
    [1] "0097_0"
    

    【讨论】:

      【解决方案2】:

      另一种方法是使用文件路径操作函数。我认为,它比正则表达式更清晰一些 - 它也可以正确处理 Windows 路径:

      # On a Linux path
      x <- "0097_abcdef/0097_0/0097_0_04_bed.dbf"
      basename( dirname(x) )
      # [1] "0097_0"
      
      # On a Windows path
      y <- "c:\\0097_abcdef\\0097_0\\0097_0_04_bed.dbf"
      basename( dirname(y) )
      # [1] "0097_0"
      

      ..它们是矢量化的,因此您可以给它们一个路径向量。 为了完整起见,还有file.path将零件重新缝合在一起。

      【讨论】:

        【解决方案3】:

        您可以轻松地改用strsplit。例如,

        R> x = "0097_abcdef/0097_0/0097_0_04_bed.dbf"
        R> strsplit(x, "/")
        [[1]]
        [1] "0097_abcdef"       "0097_0"            "0097_0_04_bed.dbf"
        
        R> strsplit(x, "/")[[1]][2]
        [1] "0097_0"
        

        【讨论】:

          【解决方案4】:

          你可以使用 read.table:

          tc <- textConnection(dbf.files)
          y <- read.table(tc,sep="/",as.is=TRUE)[2]
          close(tc)
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2015-07-29
            • 1970-01-01
            • 1970-01-01
            • 2015-07-28
            • 1970-01-01
            相关资源
            最近更新 更多