R函数中递归`list.files()`调用的有效策略

问题描述 投票:0回答:1

我有一个文件夹,将从远程站接收原始数据。数据结构主要由获取日期控制,其通用格式为:]

root/unit_mac_address/date/data_here/

这是一个有限的tree通话,需要录音几天的示例。

.
├── 2020-04-03
│   ├── 2020-04-03T11-01-31_capture.txt
│   ├── 2020-04-03T11-32-36_capture.txt
│   ├── 2020-04-03T14-58-43_capture.txt
│   ├── img
│   └── temperatures.csv
...
├── 2020-05-21
│   ├── 2020-05-21T11-10-55_capture.txt
│   ├── img
│   └── temperatures.csv
└── dc:a6:32:2d:b8:62_ip.txt

在每个img文件夹中,我有成千上万的图像都带有采集日期时间。

我的目标是将temperatures.csv中所有单位的数据合并到target_date

我目前的做法是:

# from root dir, get all the temperatures.csv files
all_files <- list.files(pattern = "temperatures.csv",
 full.names = TRUE,
 # do it for all units 
 recursive = TRUE)
# subset the files from the list that contain the target_date
all_files <- all_files[str_detect(all_files, target_date)]
# read and bind into df
df <- lapply(all_files, function(tt) read_csv(tt)) %>%
    bind_rows()

我选择搜索temperatures.csv是因为它没有加时间戳,但我想无论如何我也要遍历所有img。我认为没有办法将list.files()限制在一定水平或递归。

这有效,但这是最好的方法吗?可以采取什么措施来提高性能?每天都有数据输入,因此10-20个单元中的每个单元都需要处理越来越多的list.files()功能的文件。

temperature.csv文件本身带有时间戳(2020-05-26_temperatures.csv)会更有效吗?我可以在temperatures.csv文件本身上请求时间戳(不是当前方法),但我认为我应该可以自己解决。

仅查找具有target_date的目录会更有效吗?然后构建路径,以便仅在每个target_date目录上查看第一级?任何暗示这样做的赞赏。

r performance
1个回答
0
投票

使用评论作为一个很好的指南,这是替代方法的基准测试。

这是新功能的要点

all_units <- list.dirs(recursive = FALSE)
# mac address has ":" unlikely in anothed dir
all_units <- all_units[str_detect(all_units, ":")]
all_dirs <- lapply(all_units,
 function(tt) list.dirs(path = tt, recursive = FALSE)) %>%
    unlist()
# there shouldn't be children but
# we paste0 to only get the date folder and not the children of that folder
relevant_dirs <- all_dirs[str_detect(all_dirs, paste0(target_date, "$"))]
all_files <- lapply(relevant_dirs,
 function(tt) 
   list.files(tt, pattern = "temperatures.csv", full.names = TRUE)) %>%
    unlist()
df <- lapply(all_files, function(tt) read_csv(tt)) %>%
    bind_rows()

这里是目标日期仅以2个单位获取数据的实际基准,我怀疑递归选项的差异只会随时间而变大。

unit: milliseconds
        expr       min        lq      mean    median        uq      max neval
   read_data 111.76401 124.17692 130.59572 127.84681 133.35566 317.6134  1000
 read_data_2  39.72021  46.58495  50.80255  49.05811  52.01692 141.2126  1000
© www.soinside.com 2019 - 2024. All rights reserved.