【问题标题】:Extracting a numeric value from multiple filename in R从R中的多个文件名中提取数值
【发布时间】:2017-05-12 08:59:19
【问题描述】:

我正在尝试从多个文件名中提取一个数值,例如我有诸如 abc_2.csv 之类的文件名; pow_4.csv; foo_5.csv...等等,我试图只从文件名中提取最后一个数值。我曾尝试一次提取一个文件,但想要完全这样做,这就是我尝试过的

单个文件

>nop <- basename("D:/files/abc_2.csv")
>nop <- as.numeric(gsub("\\D+", "", nop))
>nop
  2

多个文件

setwd("D:/files")
temp = list.files(pattern="*.csv")
myfiles = lapply(temp, read.delim)

提前谢谢...

【问题讨论】:

  • 你的“单文件”代码和“多文件”代码没有远程尝试做同样的事情

标签: r regex csv filenames


【解决方案1】:

您需要来自库 stringistri_extract_last(...)

library('stringi')
t = c("abc_2.csv","pow_4.csv","foo_5.csv")

stri_extract_last(t, regex = "(\\d+)")

【讨论】:

    【解决方案2】:

    我们可以从base R使用regmatches/regexpr

    regmatches(t, regexpr( "\\d+", t))
    #[1] "2" "4" "5"
    

    如果是最后一个要提取的数字

    sub(".*(\\d+)\\D+$", "\\1", t)
    

    sapply(regmatches(t, gregexpr( "\\d+", t)), tail, 1)
    

    数据

    t <- c("abc_2.csv","pow_4.csv","foo_5.csv")
    

    【讨论】:

    • 实际上此解决方案仅返回字符串中的 first 数值,而不是问题语句中要求的 last。试试数据t &lt;- c("asdf_1_2.csv", "asdf_3_4.csv")
    • @TurtleIzzy 我们可以使用subsub(".*(\\d+)\\D+$", "\\1", t)# [1] "2" "4" 或使用其他解决方案sapply(regmatches(t, gregexpr( "\\d+", t)), tail, 1)# [1] "2" "4"
    • 这实际上通过小修改解决了问题。 sub(".*?(\\d+)\\D+$", "\\1", t) 工作。
    • 我没有,我不认为那是我。
    • @TurtleIzzy 谢谢你的回复。
    【解决方案3】:

    只是扩展您的解决方案:

    setwd("D:/location")
    temp = list.files(pattern=".*_\\d+.csv") # this will ensure only the selective files(with the specified pattern) are chosen, and not all the files in directory
    unlist(lapply(temp, function(x) gsub( "(.*_|\\.csv)", "", x)))
    #[1] "2" "4" "5"
    

    【讨论】:

      猜你喜欢
      • 2023-02-05
      • 2013-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多