【发布时间】:2022-08-18 18:08:09
【问题描述】:
我需要将很多文件加载到 R 中,所有这些文件的名称中都隐藏了一个日期,如下所示: SD07_TWK_20190822_003004
我想选择根据这些日期加载的文件。
我像这样将文件加载到 R 中:
filenames = list.files(path=path, pattern=\".txt\")
colnamesfull = c(\"time\",\"v\",\"a\",\"t1\",\"t2\",\"t3\",\"t4\",\"t5\",\"t6\",\"t7\",\"t8\")
for(i in filenames){
filepath = file.path(path, paste(i, sep=\"\"))
assign(i, read.table(filepath,
skip= 20,
col.names= colnamesfull,
sep=\",\")
)}
为了过滤日期,我假设我需要在 list.files 函数的 \'pattern\' 中添加一个日期范围。但是,我无法让它发挥作用。
假设我有以下日期:
date_start = \"20190822\"
date_end = \"20190823\"
如何将这些日期的过滤器添加到上面的代码中?
代码和文件示例:
#path = \"C:/path\"
filenames = list.files(path=path, pattern=\".txt\")
names = substr(filenames,10,17)
date_start = \"20190822\"
date_end = \"20190822\"
for(i in filenames){
filepath = file.path(path, paste(i, sep=\"\"))
if( (date_start <= names &&
names <= date_end)){
assign(i, read.table(filepath, skip=20, col.names = colnamesfull, sep=\",\"))
}
}
一些文件:
> dput(file1)
structure(list(time = c(2, 3.9, 5.8, 7.8, 9.7, 11.7, 13.6, 15.5,
17.5, 19.4), v = c(14.82, 14.804, 14.82, 14.82, 14.804, 14.82,
14.812, 14.804, 14.8, 14.808), a = c(1.5, 1.476, 1.5, 1.491,
1.452, 1.476, 1.478, 1.44, 1.454, 1.438), t1 = c(14.61, 14.61,
14.61, 14.61, 14.61, 14.61, 14.61, 14.62, 14.62, 14.63), t2 = c(14.63,
14.62, 14.62, 14.62, 14.62, 14.62, 14.62, 14.63, 14.63, 14.64
), t3 = c(14.63, 14.63, 14.63, 14.63, 14.63, 14.63, 14.63, 14.63,
14.64, 14.65), t4 = c(14.65, 14.65, 14.65, 14.65, 14.64, 14.64,
14.65, 14.65, 14.66, 14.67), t5 = c(14.65, 14.65, 14.65, 14.65,
14.65, 14.65, 14.66, 14.66, 14.67, 14.69), t6 = c(14.63, 14.63,
14.63, 14.63, 14.63, 14.63, 14.63, 14.64, 14.65, 14.66), t7 = c(14.64,
14.64, 14.64, 14.64, 14.64, 14.64, 14.64, 14.64, 14.65, 14.66
), t8 = c(14.6, 14.6, 14.6, 14.6, 14.6, 14.6, 14.61, 14.61, 14.62,
14.63)), row.names = c(NA, 10L), class = \"data.frame\")
> dput(file2)
structure(list(time = c(2, 3.9, 5.9, 7.8, 9.7, 11.7, 13.6, 15.6,
17.5, 19.5), v = c(14.808, 14.808, 14.816, 14.816, 14.808, 14.804,
14.816, 14.8, 14.808, 14.808), a = c(1.478, 1.472, 1.491, 1.49,
1.47, 1.484, 1.452, 1.473, 1.465, 1.482), t1 = c(14.63, 14.63,
14.63, 14.63, 14.62, 14.62, 14.63, 14.63, 14.63, 14.64), t2 = c(14.64,
14.64, 14.64, 14.64, 14.64, 14.64, 14.64, 14.64, 14.65, 14.65
), t3 = c(14.65, 14.65, 14.65, 14.65, 14.65, 14.64, 14.65, 14.65,
14.65, 14.66), t4 = c(14.66, 14.66, 14.66, 14.66, 14.66, 14.66,
14.66, 14.67, 14.67, 14.68), t5 = c(14.67, 14.67, 14.67, 14.67,
14.67, 14.67, 14.67, 14.68, 14.69, 14.7), t6 = c(14.65, 14.65,
14.65, 14.65, 14.65, 14.65, 14.65, 14.65, 14.66, 14.67), t7 = c(14.65,
14.65, 14.65, 14.65, 14.65, 14.65, 14.65, 14.66, 14.66, 14.67
), t8 = c(14.62, 14.62, 14.62, 14.62, 14.62, 14.62, 14.62, 14.62,
14.63, 14.64)), row.names = c(NA, 10L), class = \"data.frame\")