从R中的多个文件名中提取数值
Extracting a numeric value from multiple filename in R
我正在尝试从多个文件名中提取一个数值,例如我有 abc_2.csv 这样的文件名; pow_4.csv; foo_5.csv...依此类推,我试图仅从文件名中提取最后一个数值。我试过一次提取一个文件,但想完全提取,这就是我尝试过的
single file
>nop <- basename("D:/files/abc_2.csv")
>nop <- as.numeric(gsub("\D+", "", nop))
>nop
2
for multiple files
setwd("D:/files")
temp = list.files(pattern="*.csv")
myfiles = lapply(temp, read.delim)
提前致谢...
您需要图书馆 stringi
中的 stri_extract_last(...)
。
library('stringi')
t = c("abc_2.csv","pow_4.csv","foo_5.csv")
stri_extract_last(t, regex = "(\d+)")
我们可以使用 regmatches/regexpr
从 base R
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")
只是扩展您的解决方案:
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"
我正在尝试从多个文件名中提取一个数值,例如我有 abc_2.csv 这样的文件名; pow_4.csv; foo_5.csv...依此类推,我试图仅从文件名中提取最后一个数值。我试过一次提取一个文件,但想完全提取,这就是我尝试过的
single file
>nop <- basename("D:/files/abc_2.csv")
>nop <- as.numeric(gsub("\D+", "", nop))
>nop
2
for multiple files
setwd("D:/files")
temp = list.files(pattern="*.csv")
myfiles = lapply(temp, read.delim)
提前致谢...
您需要图书馆 stringi
中的 stri_extract_last(...)
。
library('stringi')
t = c("abc_2.csv","pow_4.csv","foo_5.csv")
stri_extract_last(t, regex = "(\d+)")
我们可以使用 regmatches/regexpr
从 base R
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")
只是扩展您的解决方案:
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"