从 R 中的文件名读取日期并追加



我的文件夹中有以下文件

UPS_REPLEN_ORDERS_09102017_A
UPS_REPLEN_ORDERS_10102017_A
UPS_REPLEN_ORDERS_11102017_A

再过60天。

我需要从相应的文件中提取日期并插入该文件的数据列,然后附加所有 60 天的文件。

你能更具体地说明你的最终目标吗?

这是一种使用正则表达式将文件放入 R 的方法,并通过 substr 从其名称中提取日期。由于我不明白您在将文件和日期拉入 R 后如何处理它们的意思,因此我无法帮助您执行后续步骤。

我假设您已将所有目标文件保存到可访问的目录中,所有文件都遵循您在此处给出的约定(即,它们以"UPS_REPLEN_ORDERS_"开头,后跟 8 位日期,后跟一些其他字符,可能包括文件扩展名),并且目录中没有其他文件遵循此命名约定。

#set your working directory to wherever you've stored the files
setwd(dirname)
#declare your filename pattern using regular expressions
fpattern="^UPS_REPLEN_ORDERS_.*\"
#find names matching this pattern in your current working directory
fnames=dir(getwd(),pattern=fpattern)
#extract the date from each filename
fdates=substr(fnames,19,26)
#loop to read files into R and modify as needed
nfiles=length(fnames)
for (i in 1:nfiles){
  infile=read.table(fnames[i]) #set read parameters as you need
  #other operations to be performed on the newly read-in file...
}

最新更新