以更紧凑的方式组合多个数据集

Combine multiple datasets in a more compact way

每当我有多个数据集要加载并组合成一个数据集,以便我可以同时分析所有这些数据集时,我会做类似

的事情
for(i in 1:length(dataset_paths))
{
  data_path <- list.files(path = paste0(here(dataset_paths[i]), "results/analysis/"), pattern = ".*\.degradation_dynamics\.csv", full.names = TRUE)
  t_dt <- fread(data_path)
  if(i == 1)
  {
    dt <- t_dt
  }
  dt <- rbind(dt, t_dt)
}
rm(t_dt)
dt %>% setkey(frame)

这段代码相当难看

有没有办法让这段代码更小更容易理解?

例如

请注意,以下代码未经过测试,但使用 lapply 您可以执行以下操作:

dt <- lapply(dataset_paths, function(x) {
  data_path <- list.files(path = here(x, "results", "analysis"), pattern = ".*\.degradation_dynamics\.csv", full.names = TRUE)
  fread(data_path)
})
dt <- do.call(rbind, dt)
dt %>% setkey(frame)

出于这个目的我喜欢foreach

require(data.table)
require(foreach)

dt <- foreach( path = dataset_paths, .combine='rbind' ) %do% {
  
  dt_t <- fread(path)
  
}

setkey(dt,frame)