Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从R中的多个文件名中提取数值_R_Regex_Csv_Filenames - Fatal编程技术网

从R中的多个文件名中提取数值

从R中的多个文件名中提取数值,r,regex,csv,filenames,R,Regex,Csv,Filenames,我试图从多个文件名中提取一个数值,例如,我有一些文件名,如abc_2.csv;pow_4.csv;csv…等等,我试图从文件名中只提取最后一个数值。我曾经尝试过一次提取一个文件,但我想把它作为一个整体来做,这就是我尝试了一个文件的原因 单个文件 提前感谢…您需要从库stringi中提取最后一个(…) library('stringi') t = c("abc_2.csv","pow_4.csv","foo_5.csv") stri_extract_last(t, regex = "(\\d+)

我试图从多个文件名中提取一个数值,例如,我有一些文件名,如abc_2.csv;pow_4.csv;csv…等等,我试图从文件名中只提取最后一个数值。我曾经尝试过一次提取一个文件,但我想把它作为一个整体来做,这就是我尝试了一个文件的原因

单个文件


提前感谢…

您需要从库
stringi
中提取最后一个(…)

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

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

您需要从库
stringi
中提取最后一个(…)

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

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

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

regmatches(t, regexpr( "\\d+", t))
#[1] "2" "4" "5"
如果是最后一个要提取的数字

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

数据
t我们可以使用
regmatches/regexpr
from
base R

regmatches(t, regexpr( "\\d+", t))
#[1] "2" "4" "5"
如果是最后一个要提取的数字

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

数据
t只是扩展您的解决方案:

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"

只是扩展您的解决方案:

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"

您的“单文件”代码和“多文件”代码未远程尝试执行相同的操作您的“单文件”代码和“多文件”代码未远程尝试执行相同的操作实际上,此解决方案仅返回字符串中的第一个数值,而不是问题语句中要求的最后一个数值。尝试使用
sub
可以实现的数据
t@turtleizy,即
sub(.*(\\d+\\d+$),“\\1”,t)#[1]“2”“4”
或使用另一种解决方案
sapply(regmatches(t,gregexpr(\\d+”,t)),tail,1)#[1]“2”“4”
,只需稍加修改即可解决问题
sub(“.*(\\d+\\d+$”,“\\1”,t)
有效。我不,我不认为那是我。@Turtlezzy感谢您的回复。实际上,此解决方案只返回字符串中的第一个数值,而不是问题语句中要求的最后一个数值。尝试使用
sub
可以实现的数据
t@turtleizy,即
sub(.*(\\d+\\d+$),“\\1”,t)#[1]“2”“4”
或使用另一种解决方案
sapply(regmatches(t,gregexpr(\\d+”,t)),tail,1)#[1]“2”“4”
,只需稍加修改即可解决问题
sub(“.*(\\d+\\d+$”,“\\1”,t)
有效。我不,我不认为那是我。@Turtlezzy谢谢你的回复。